// EnergyPlus, Copyright (c) 1996-2025, The Board of Trustees of the University of Illinois,
// The Regents of the University of California, through Lawrence Berkeley National Laboratory
// (subject to receipt of any required approvals from the U.S. Dept. of Energy), Oak Ridge
// National Laboratory, managed by UT-Battelle, Alliance for Sustainable Energy, LLC, and other
// contributors. All rights reserved.
//
// NOTICE: This Software was developed under funding from the U.S. Department of Energy and the
// U.S. Government consequently retains certain rights. As such, the U.S. Government has been
// granted for itself and others acting on its behalf a paid-up, nonexclusive, irrevocable,
// worldwide license in the Software to reproduce, distribute copies to the public, prepare
// derivative works, and perform publicly and display publicly, and to permit others to do so.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted
// provided that the following conditions are met:
//
// (1) Redistributions of source code must retain the above copyright notice, this list of
//     conditions and the following disclaimer.
//
// (2) Redistributions in binary form must reproduce the above copyright notice, this list of
//     conditions and the following disclaimer in the documentation and/or other materials
//     provided with the distribution.
//
// (3) Neither the name of the University of California, Lawrence Berkeley National Laboratory,
//     the University of Illinois, U.S. Dept. of Energy nor the names of its contributors may be
//     used to endorse or promote products derived from this software without specific prior
//     written permission.
//
// (4) Use of EnergyPlus(TM) Name. If Licensee (i) distributes the software in stand-alone form
//     without changes from the version obtained under this License, or (ii) Licensee makes a
//     reference solely to the software portion of its product, Licensee must refer to the
//     software as "EnergyPlus version X" software, where "X" is the version number Licensee
//     obtained under this License and may not use a different name for the software. Except as
//     specifically required in this Section (4), Licensee shall not use in a company name, a
//     product name, in advertising, publicity, or other promotional activities any name, trade
//     name, trademark, logo, or other designation of "EnergyPlus", "E+", "e+" or confusingly
//     similar designation, without the U.S. Department of Energy's prior written consent.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

// C++ Headers
#include <cmath>
#include <string>

// ObjexxFCL Headers
#include <ObjexxFCL/Array.functions.hh>
#include <ObjexxFCL/Array2D.hh>
// #include <ObjexxFCL/Fmath.hh>

// EnergyPlus Headers
#include <EnergyPlus/BranchNodeConnections.hh>
#include <EnergyPlus/CurveManager.hh>
#include <EnergyPlus/Data/EnergyPlusData.hh>
#include <EnergyPlus/DataEnvironment.hh>
#include <EnergyPlus/DataHVACGlobals.hh>
#include <EnergyPlus/DataHeatBalFanSys.hh>
#include <EnergyPlus/DataHeatBalance.hh>
#include <EnergyPlus/DataIPShortCuts.hh>
#include <EnergyPlus/DataLoopNode.hh>
#include <EnergyPlus/DataWater.hh>
#include <EnergyPlus/DataZoneEnergyDemands.hh>
#include <EnergyPlus/DataZoneEquipment.hh>
#include <EnergyPlus/EMSManager.hh>
#include <EnergyPlus/FluidProperties.hh>
#include <EnergyPlus/General.hh>
#include <EnergyPlus/GlobalNames.hh>
#include <EnergyPlus/HeatBalanceInternalHeatGains.hh>
#include <EnergyPlus/InputProcessing/InputProcessor.hh>
#include <EnergyPlus/NodeInputManager.hh>
#include <EnergyPlus/OutAirNodeManager.hh>
#include <EnergyPlus/OutputProcessor.hh>
#include <EnergyPlus/Plant/DataPlant.hh>
#include <EnergyPlus/PlantUtilities.hh>
#include <EnergyPlus/Psychrometrics.hh>
#include <EnergyPlus/RefrigeratedCase.hh>
#include <EnergyPlus/ScheduleManager.hh>
#include <EnergyPlus/UtilityRoutines.hh>
#include <EnergyPlus/WaterManager.hh>

namespace EnergyPlus::RefrigeratedCase {

// MODULE INFORMATION:
//       AUTHOR         Richard Raustad, FSEC
//       DATE WRITTEN   Oct/Nov 2004
//       MODIFIED       Shirey, FSEC Dec 2004; Hudson, ORNL Feb 2007, July 2007
//       MODIFIED       Stovall, ORNL, April 2008 added detailed refrigeration systems
//       MODIFIED       Stovall, ORNL, Fall 2009 added cascade condensers, secondary loops, and walk-ins.
//       MODIFIED       Griffith, NREL, 2010, Plant upgrade, generalize plant fluid properties.
//       MODIFIED       Fricke, ORNL, Fall 2011, added detailed transcritical CO2 refrigeration system.
//       RE-ENGINEERED  na

// PURPOSE OF THIS MODULE:
// To simulate refrigerated cases,walk-in coolers, secondary loops,
//             compressor racks, and detailed refrigeration systems.
// Case performance is varied based on specific operating conditions within the zone.

// METHODOLOGY EMPLOYED:
// Refrigerated cases are simulated based on performance information available from manufacturers
// and knowing the latent heat ratio of the case cooling load which can be obtained from ASHRAE or
// others who have completed research to quantify this value. The sensible case credits
// (sensible cooling provided to the surrounding zone air) are calculated during input
// processing by subtracting the fan, lighting, and anti-sweat heater energy from the
// design sensible capacity (TotCap * (1-LHR) * RTF).  The actual latent cooling provided
// by the case (at the actual operating conditions) is calculated based on the latent performance
// curve supplied by the user.  The actual sensible cooling provided by the case (at the actual
// operating conditions) is calculated by summing all sensible components (fan + light + anti-sweat +
// sensible case credit). The case (evaporator) fans are assumed to be disabled during hot-gas or
// electric defrost modes. A stocking schedule (W/m) is available for added load if desired.
// Walk-In coolers are simulated based on the specified sum of the conductance*area of each wall and door facing
// up to three (extensible) zones.  Two types of doors are specified, stock doors and glass doors.  For each category
// of doors, schedules for door openings are used with ASHRAE models for infiltration
// which are a function of the height of the door.  That
// infiltration is used to calculate the latent load on the cooler and the latent case credits for each zone.
// The sensible case credit for each zone is the sum of the conductive and sensible infiltration load
// for each surface/door facing that zone.  Note that the latent portion of the infiltration is unused
// during defrost to be consistent with decision for refrigerated cases.
// Compressor racks are simulated by summing the attached refrigerated case and walk-in cooler
// capacities.  The energy use of the
// compressor rack is then calculated with a simplified model for COP variation with temperature. Condenser fan power
// is based on a user-supplied curve object. Racks are not scheduled.
// Compressor racks may have indoor (in-zone) or outdoor condensers.  If outdoors, the condensers may be cooled
// by dry air cooling or evaporative cooling. A water-cooled condenser is also available by specifying water-cooling
// as the Condenser Type.  If a water-cooled condenser is utilized, a second entry to this module will
// occur during the HVAC simulation as called from the NonZoneEquipmentManager.
// Detailed refrigeration systems model each compressor individually using the manufacturer's rating curves.
// A collection of such curves has been added in the datasets library. The curves produce the refrigeration
// capacity and power consumption. The capacity needed is based on the sum of the case and walk-in loads (as is done
// for the compressor racks).  The compressors are dispatched to meet this load according to the order
// prescribed in the compressor list input object. The condenser for each system can be air-cooled,
// evaporative-cooled, or water cooled.  For air and evap-cooled condensers, manufacturer's rating data
// is input to describe the performance and to determine the required air flow rate, which is used to
// calculate the fan power requirements.  The fans can be described as single-speed, two-speed, or variable
// speed. The condenser performance data also is used to calculate the condensing temperature, which is a function
// of the heat sink temperature and the load on the condenser.  This must be solved iteratively, checking on
// the calculated refrigerant mass flow through the compressors.  The solution usually requires less than 5 iterations.
// The refrigerant state exiting the compressor group is known so the amount of heat available for
// desuperheat reclaim is explicitly known.
// The detailed refrigeration model allows the use of subcoolers,secondary loops, and cascade condensers
// to transfer load from one suction group to another. This introduces the need for further iterations among
// the systems.  Three loops through the
// systems are adequate to model these interactions.  The detailed model will also calculate a variable suction
// pressure for systems with controls that allow the suction temperature/pressure to float
// up when the case loads are less than their design capacity.

// Secondary Systems include case and walk-in refrigeration loads.  However, the balance of the system is
// made up of a heat exchanger and circulating pump(s) instead of a condenser and compressors.
// The total load on the heat exchanger is the sum of the refrigeration loads, any pipe heat gains,
// and the portion of the pump power that is absorbed by the circulating fluid. If the total load is
// greater than the rated capacity of the secondary loop, the unmet load for any time step is carried over
// to the next time step.  Each secondary system appears as a load on a detailed refrigeration system. If
// any of the cases or walk-ins served by a secondary are defrosted using hot brine, the primary system
// serving the secondary loop receives the defrost energy credits (i.e., heat reclaim used to generate defrost
// energy).

// Cascade Condensers allow the use of a higher temperature refrigeration system (primary system) to serve as a
// heat rejection sink for a lower temperature refrigeration system (secondary system). The condensing
// temperature can be fixed or can be allowed to float according to the minimum required evaporating temperature
// for other loads upon the primary system. For cases and walk-ins served by cascade condensers, energy associated
// with hot gas defrost is reclaimed from the primary system.  The refrigeration load the cascade condenser
// places upon the primary system is the sum of all case and walk-in loads served by the secondary system plus
// the sum of the secondary loop's compressor power. The same name used to identify the condenser in the
// secondary loop is used to identify the cascade load on the primary system.

// Detailed transcritical CO2 refrigeration systems model each compressor individually using the manufacturer's
// performance data. A collection of CO2 compressor performance curves has been added in the datasets library.
// The curves produce the refrigeration capacity and power consumption. The capacity required is based on the sum
// of the case and walk-in loads and the compressors are dispatched to meet this load according to the order
// prescribed in the compressor list input object. Currently, an air-cooled gas cooler is modeled, and
// manufacturer's rating data is input to describe the performance and to determine the required fan power
// requirements. The gas cooler fans can be described as single-speed, two-speed, or variable speed. During
// transcritical operation, the optimal gas cooler pressure, which maximizes the system's COP, is determined as
// a function of the ambient air temperature. During subcritical operation, the condensing pressure is allowed to
// float with ambient temperature in order to achieve maximum performance.

// This module was designed to be accessed once for each time step.  It uses several accumulating variables
//  to carry unmet loads from one time step to the next (cases/walk-ins and compressors.  Also, it meets
//  heat reclaim needs with the loads from the previous time step (because they are unknown for the current
//  zone time step).  However, the loads time step may be repeated, such as when a demand manager is used.
//  For that purpose, the values for these accumulating variables are saved at the start of each time step
//  and reset whenever the time step is repeated.  (see the init subroutine.)
// This correction is also applied when working on the system time step for coil-type loads by setting the saved values
//  at the start of each system time step to the value at the end of the previous time step. They are reset
//  to that value at each sys time step iteration. (see InitRefrigeration)

// REFERENCES:
// Specific references are provided for the equipment simulation subroutines below.

// True at the start of each time step, False after first subtime step of time step
// includes DataGlobals::CurrentTime, in fractional hours, from start of day. Uses Loads time step.
// includes DataGlobals::NumOfZones

// Following constant approp for R22, future may make f(refrigerant)
Real64 constexpr CaseSuperheat(4.0);       // case superheat used to control thermal expansion valve, ASHRAE 2006 p 44.6 (C)
Real64 constexpr TransCaseSuperheat(10.0); // case superheat for transcritical CO2 systems (C)

// Next two constants used to autosize evap condenser
Real64 constexpr CondPumpRatePower(0.004266);  // evap condenser pump rated, Wpump/Wcapacity (15 W/ton)
Real64 constexpr AirVolRateEvapCond(0.000144); // evap cond air flow rate for autosize, equiv 850 cfm/ton (m3/W-s)
Real64 constexpr EvapCutOutTdb(4.0);           // shut off evap water flow if outdoor drybulb < evapcutOutTdb (C)

// Miscellaneous constants
Real64 constexpr MyLargeNumber(1.0e9);
Real64 constexpr MySmallNumber(1.0e-9);
Real64 constexpr Rair(0.3169);                   // Air resistance used with Heat Balance anti-sweat (AS) heater
Real64 constexpr IceMeltEnthalpy(335000.0);      // heat of fusion of water J/kg
Real64 constexpr TempTooHotToFrost(5.0);         // C, used to check for frosting conditions on evaporator coils
Real64 constexpr IcetoVaporEnthalpy(2833000.0);  // J/kg to freeze water vapor to ice
Real64 constexpr SpecificHeatIce(2000.0);        // in the likely range (2040 at 0C and 1950 at -20C) (J/kg-C)
Real64 constexpr CondAirVolExponentDry(1.58);    // exponent for forced air over a cylinder, = 1/.633 per ASHRAE 2005 (page 3.15)
Real64 constexpr CondAirVolExponentEvap(1.32);   // exponent for evap condenser air vol flow, = 1/.76 per Manske, 1999
Real64 constexpr EvaporatorAirVolExponent(1.54); // exponent for evaporator air vol flow, = 1/.65 per Manske, 1999, page 35
Real64 constexpr FanHalfSpeedRatio(0.1768);      // = 1/(2**2.5) for power step for two speed fan
Real64 constexpr CapFac60Percent(0.60);          // = 60%, load served by half power 2-speed fan

static constexpr std::array<Real64, 5> EuropeanWetCoilFactor = {1.35, 1.15, 1.05, 1.01, 1.0};
static constexpr std::array<Real64, 5> EuropeanAirInletTemp = {10.0, 0.0, -18.0, -25.0, -34.0};

// constexpr std::array<std::string_view, (int)WIStockDoor::Num> wiStockDoorNames = {"None", "AirCurtain", "StripCurtain"};
constexpr std::array<std::string_view, (int)WIStockDoor::Num> wiStockDoorNamesUC = {"NONE", "AIRCURTAIN", "STRIPCURTAIN"};

// constexpr std::array<std::string_view, (int)CompressorSuctionPressureCtrl::Num> compressorSuctionPressureCtrlNames = {"FloatSuctionTemperature",
//                                                                                                                      "ConstantSuctionTemperature"};
constexpr std::array<std::string_view, (int)CompressorSuctionPressureCtrl::Num> compressorSuctionPressureCtrlNamesUC = {"FLOATSUCTIONTEMPERATURE",
                                                                                                                        "CONSTANTSUCTIONTEMPERATURE"};

// constexpr std::array<std::string_view, (int)SubcoolerType::Num> subcoolerTypeNames = {"LiquidSuction", "Mechanical"};
constexpr std::array<std::string_view, (int)SubcoolerType::Num> subcoolerTypeNamesUC = {"LIQUIDSUCTION", "MECHANICAL"};

// constexpr std::array<std::string_view, (int)DefrostCtrlType::Num> defrostCtrlTypeNames = {"TimeSchedule", "TemperatureTermination"};
constexpr std::array<std::string_view, (int)DefrostCtrlType::Num> defrostCtrlTypeNamesUC = {"TIMESCHEDULE", "TEMPERATURETERMINATION"};

// constexpr std::array<std::string_view, (int)SecFluidType::Num> secFluidTypeNames = {"FluidAlwaysLiquid", "FluidPhaseChange"};
constexpr std::array<std::string_view, (int)SecFluidType::Num> secFluidTypeNamesUC = {"FLUIDALWAYSLIQUID", "FLUIDPHASECHANGE"};

// constexpr std::array<std::string_view, (int)SecPumpCtrl::Num> secPumpCtrlNames = {"Constant", "Variable"};
constexpr std::array<std::string_view, (int)SecPumpCtrl::Num> secPumpCtrlNamesUC = {"CONSTANT", "VARIABLE"};

// constexpr std::array<std::string_view, (int)EnergyEqnForm::Num> energyEqnFormNames = {
//     "None", "CaseTemperatureMethod", "RelativeHumidityMethod", "DewpointMethod"};
constexpr std::array<std::string_view, (int)EnergyEqnForm::Num> energyEqnFormNamesUC = {
    "NONE", "CASETEMPERATUREMETHOD", "RELATIVEHUMIDITYMETHOD", "DEWPOINTMETHOD"};

// constexpr std::array<std::string_view, (int)CascadeCndsrTempCtrlType::Num> cascaseCndsrTempCtrlTypeNames = {"Fixed", "Float"};
constexpr std::array<std::string_view, (int)CascadeCndsrTempCtrlType::Num> cascaseCndsrTempCtrlTypeNamesUC = {"FIXED", "FLOAT"};

// constexpr std::array<std::string_view, (int)CndsrFlowType::Num> cndsrFlowTypeNames = {"VariableFlow", "ConstantFlow"};
constexpr std::array<std::string_view, (int)CndsrFlowType::Num> cndsrFlowTypeNamesUC = {"VARIABLEFLOW", "CONSTANTFLOW"};

// constexpr std::array<std::string_view, (int)FanSpeedCtrlType::Num> fanSpeedCtrlTypeNames = {"VariableSpeed", "FixedLinear", "TwoSpeed", "Fixed"};
constexpr std::array<std::string_view, (int)FanSpeedCtrlType::Num> fanSpeedCtrlTypeNamesUC = {"VARIABLESPEED", "FIXEDLINEAR", "TWOSPEED", "FIXED"};

// constexpr std::array<std::string_view, (int)FanSpeedCtrlType::Num> heatRejLocationNames = {"Outdoors", "Zone"};
constexpr std::array<std::string_view, (int)FanSpeedCtrlType::Num> heatRejLocationNamesUC = {"OUTDOORS", "ZONE"};

// constexpr std::array<std::string_view, (int)RefCaseDefrostType::Num> refCaseDefrostTypeNames = {
//     "None", "OffCycle", "HotFluid", "HotFluidWithTemperatureTermination", "Electric", "ElectricOnDemand", "ElectricWithTemperatureTermination"};
constexpr std::array<std::string_view, (int)RefCaseDefrostType::Num> refCaseDefrostTypeNamesUC = {
    "NONE", "OFFCYCLE", "HOTFLUID", "HOTFLUIDWITHTEMPERATURETERMINATION", "ELECTRIC", "ELECTRICONDEMAND", "ELECTRICWITHTEMPERATURETERMINATION"};

// constexpr std::array<std::string_view, (int)ASHtrCtrlType::Num> asHtrCtrlTypeNames = {
//    "None", "Constant", "Linear", "DewpointMethod", "HeatBalanceMethod"};
constexpr std::array<std::string_view, (int)ASHtrCtrlType::Num> asHtrCtrlTypeNamesUC = {
    "NONE", "CONSTANT", "LINEAR", "DEWPOINTMETHOD", "HEATBALANCEMETHOD"};

// constexpr std::array<std::string_view, (int)RatingType::Num> ratingTypeNames = {"CapacityTotalSpecificConditions",
//                                                                                 "EuropeanSC1Standard",
//                                                                                 "EuropeanSC1NominalWet",
//                                                                                 "EuropeanSC2Standard",
//                                                                                 "EuropeanSC2NominalWet",
//                                                                                 "EuropeanSC3Standard",
//                                                                                 "EuropeanSC3NominalWet",
//                                                                                 "EuropeanSC4Standard",
//                                                                                 "EuropeanSC4NominalWet",
//                                                                                 "EuropeanSC5Standard",
//                                                                                 "EuropeanSC5NominalWet",
//                                                                                 "UnitLoadFactorSensibleOnly"};
constexpr std::array<std::string_view, (int)RatingType::Num> ratingTypeNamesUC = {"CAPACITYTOTALSPECIFICCONDITIONS",
                                                                                  "EUROPEANSC1STANDARD",
                                                                                  "EUROPEANSC1NOMINALWET",
                                                                                  "EUROPEANSC2STANDARD",
                                                                                  "EUROPEANSC2NOMINALWET",
                                                                                  "EUROPEANSC3STANDARD",
                                                                                  "EUROPEANSC3NOMINALWET",
                                                                                  "EUROPEANSC4STANDARD",
                                                                                  "EUROPEANSC4NOMINALWET",
                                                                                  "EUROPEANSC5STANDARD",
                                                                                  "EUROPEANSC5NOMINALWET",
                                                                                  "UNITLOADFACTORSENSIBLEONLY"};

//  constexpr std::array<std::string_view, (int)SHRCorrectionType::Num> shrCorrectionTypeNames = {
//     "LinearSHR60", "QuadraticSHR", "European", "TabularRHxDT1xTRoom"};
constexpr std::array<std::string_view, (int)SHRCorrectionType::Num> shrCorrectionTypeNamesUC = {
    "LINEARSHR60", "QUADRATICSHR", "EUROPEAN", "TABULARRHXDT1XTROOM"};

// constexpr std::array<std::string_view, (int)VerticalLoc::Num> verticalLocNames = {"Ceiling", "Middle", "Floor"};
constexpr std::array<std::string_view, (int)VerticalLoc::Num> verticalLocNamesUC = {"CEILING", "MIDDLE", "FLOOR"};

// constexpr std::array<std::string_view, (int)DefrostType::Num> defrostTypeNames = {"HotFluid", "Electric", "None", "OffCycle"};
constexpr std::array<std::string_view, (int)DefrostType::Num> defrostTypeNamesUC = {"HOTFLUID", "ELECTRIC", "NONE", "OFFCYCLE"};

// constexpr std::array<std::string_view, (int)CriticalType::Num> criticalTypeNames = {"Subcritical", "Transcritical"};
constexpr std::array<std::string_view, (int)CriticalType::Num> criticalTypeNamesUC = {"SUBCRITICAL", "TRANSCRITICAL"};

// constexpr std::array<std::string_view, (int)IntercoolerType::Num> intercoolerTypeNames = {"None", "Flash Intercooler", "Shell-and-Coil
// Intercooler"};
constexpr std::array<std::string_view, (int)IntercoolerType::Num> intercoolerTypeNamesUC = {
    "NONE", "FLASH INTERCOOLER", "SHELL-AND-COIL INTERCOOLER"};

// constexpr std::array<std::string_view, (int)IntercoolerType::Num> transSysTypeNames = {"SingleStage", "TwoStage"};
constexpr std::array<std::string_view, (int)IntercoolerType::Num> transSysTypeNamesUC = {"SINGLESTAGE", "TWOSTAGE"};

void ManageRefrigeratedCaseRacks(EnergyPlusData &state)
{

    // SUBROUTINE INFORMATION:
    //       AUTHOR         Richard Raustad, FSEC
    //       DATE WRITTEN   Oct/Nov 2004
    //       MODIFIED       Shirey, FSEC Dec 2004, Stovall, ORNL, May 2008
    //       RE-ENGINEERED  na

    // PURPOSE OF THIS SUBROUTINE:
    // This subroutine is called from HVACManager.cc, subroutine ManageHVAC to
    // manage refrigerated cases and associated compressor racks on zone time step
    // OR from SimAirChillerSet in this module on sys time step (Stovall 2011)

    // METHODOLOGY EMPLOYED:
    // Each compressor rack is modeled by first simulating the attached refrigeration loads. The
    // loads can include refrigerated cases, walk-in coolers, and secondary fluid chillers.  The sum
    // of the total heat transfer for all attached loads determines the load on the compressor rack.
    // For the refrigeration rack approach, a simple model for variation of COP with
    // condensing temperature is used to determine rack power and energy consumption.
    // For the detailed system approach, the compressors and condensers are modeled individually
    // using manufacturer's data and rated performance curves.
    // Inter-system heat transfer via subcoolers and cascade condensers can be accommodated.
    // Secondary refrigeration cycles are also available.

    auto &RefrigRack = state.dataRefrigCase->RefrigRack;

    if (!state.dataRefrigCase->ManageRefrigeration) {
        return;
    }

    CheckRefrigerationInput(state);

    InitRefrigeration(state);

    // ManageRefrigeratedCaseRacks is called on each zone time step.
    //  However, if have chillers, ManageRefrigeration will be .TRUE. and will
    //  need to bounce back. (InitRefrig has to be called anyway to zero values at zone time step.)
    //  Therefore...
    if ((!state.dataRefrigCase->HaveCasesOrWalkins) && (!state.dataRefrigCase->UseSysTimeStep)) {
        // Zero requests for cooling water from plant or tank
        ZeroHVACValues(state);
        return;
    }
    // Following case should never occur, but just for completeness:
    if ((!state.dataRefrigCase->HaveChillers) && (state.dataRefrigCase->UseSysTimeStep)) {
        return;
    }

    // Refrigerated cases are not simulated the first time through, replicate this on beginning of next environment
    if (state.dataGlobal->BeginEnvrnFlag && state.dataRefrigCase->MyEnvrnFlag) {
        state.dataRefrigCase->MyEnvrnFlag = false;
        return;
    }
    if (!state.dataGlobal->BeginEnvrnFlag) {
        state.dataRefrigCase->MyEnvrnFlag = true;
    }

    if (state.dataRefrigCase->HaveRefrigRacks) {
        for (int RackNum = 1; RackNum <= state.dataRefrigCase->NumRefrigeratedRacks; ++RackNum) {
            RefrigRack(RackNum).CalcRackSystem(state);
            RefrigRack(RackNum).ReportRackSystem(state, RackNum);
        }
    }

    if (state.dataRefrigCase->HaveDetailedRefrig) {
        SimulateDetailedRefrigerationSystems(state);
    }
    if (state.dataRefrigCase->HaveDetailedTransRefrig) {
        SimulateDetailedTransRefrigSystems(state);
    }
}

void GetRefrigerationInput(EnergyPlusData &state)
{

    // SUBROUTINE INFORMATION:
    //       AUTHOR         Richard Raustad, FSEC
    //       DATE WRITTEN   Oct/Nov 2004
    //       MODIFIED       Shirey, FSEC Dec 2004; Hudson, ORNL Feb 2007, July 2007
    //       MODIFIED       Stovall, ORNL April 2008, Assisted by Hugh Henderson
    //       RE-ENGINEERED  na

    // PURPOSE OF THIS SUBROUTINE:
    // GetObjectItem is called to read refrigerated case, rack, compressor, and condenser information
    // Lists of cases and compressors are then correlated to the appropriate system.
    // The nominal ratings of all components are then compared and a warning is printed if the system is not balanced

    // METHODOLOGY EMPLOYED:
    // GetObjectItem is called to read refrigerated case information

    static constexpr std::string_view TrackMessage("from refrigerated case");
    static constexpr std::string_view RoutineName("GetRefrigerationInput: ");
    static constexpr std::string_view routineName = "GetRefrigerationInput";
    static constexpr std::string_view TrackMessageAlt("GetInput in RefrigeratedCase");

    //     input in both watts and flow rate
    int constexpr NumWIAlphaFieldsBeforeZoneInput(9);   // Used to cycle through zones on input for walk in coolers
    int constexpr NumWIAlphaFieldsPerZone(4);           // Used to cycle through zones on input for walk in coolers
    int constexpr NumWINumberFieldsBeforeZoneInput(12); // Used to cycle through zones on input for walk in coolers
    int constexpr NumWINumberFieldsPerZone(8);          // Used to cycle through zones on input for walk in coolers
    Real64 constexpr CondARI460DelT(16.7);              // Rated sat cond temp - dry bulb air T for air-cooled Condensers, ARI460
    Real64 constexpr CondARI460Tcond(51.7);             // Rated sat cond temp for air-cooled cond, ARI 460
    Real64 constexpr CondARI490DelT(15.0);              // Rated sat cond temp - wet bulb air T for evap-cooled Cond w R22, ARI490
    Real64 constexpr CondARI490Tcond(40.6);             // Rated sat cond temp for evap-cooled cond with R22, ARI 490
    Real64 constexpr DelEvapTDefault(5.0);              // default difference between case T and evap T (C)
    Real64 constexpr DefaultCascadeCondApproach(3.0);   // Cascade condenser approach temperature difference (deltaC)
    Real64 constexpr DefaultCircRate(2.5);              // Phase change liquid overfeed circulating rate (ASHRAE definition)
    Real64 constexpr DefaultWISurfaceUValue(0.3154);    // equiv R18 in Archaic American units (W/m2-delta T)
    Real64 constexpr DefaultWIUValueGlassDr(1.136);     // equiv R5 in Archaic American units (W/m2-delta T)
    Real64 constexpr DefaultWIUValueStockDr(0.3785);    // equiv R15 in Archaic American units (W/m2-delta T)
    Real64 constexpr DefaultWIHeightGlassDr(1.5);       // glass door height in walk-in cooler (m)
    Real64 constexpr DefaultWIHeightStockDr(3.0);       // stock door height in walk-in cooler (m)
    Real64 constexpr PumpImpellerEfficiency(0.78);      // same as used in pump auto-sizing, dimensionless
    Real64 constexpr PumpMotorEfficiency(0.85);         // suggested as average value in ITT/Gould pump references,

    Array1D_string Alphas;             // Alpha items for object
    Array1D_string cAlphaFieldNames;   // Alpha field names (from input processor)
    Array1D_string cNumericFieldNames; // Numeric field names (from input processor)
    std::string CurrentModuleObject;   // Object type for getting and error messages

    Array1D_bool lAlphaBlanks;   // Logic array, alpha input blank = .TRUE.
    Array1D_bool lNumericBlanks; // Logic array, numeric input blank = .TRUE.
    bool ErrorsFound(false);     // Set to true if errors in input, fatal at end of routine

    int AlphaNum(0);                       // Used to cycle through input
    int IOStatus(0);                       // Used in GetObjectItem
    int MaxNumAlphasRack(0);               // Maximum number of alphas for rack object
    int MaxNumAlphasAirChiller(0);         // Maximum number of alphas for air chiller
    int MaxNumAlphasAll(0);                // Maximum number of alphas for all objects
    int MaxNumAlphasSys(0);                // Maximum number of alphas for system object
    int MaxNumAlphasTransSys(0);           // Maximum number of alphas for transcritical system object
    int MaxNumAlphasChillerSet(0);         // Maximum number of alphas for chiller set
    int MaxNumAlphasConda(0);              // Maximum number of alphas for air-cooled condenser object
    int MaxNumAlphasConde(0);              // Maximum number of alphas for evap-cooled condenser object
    int MaxNumAlphasCondw(0);              // Maximum number of alphas for water-cooled condenser object
    int MaxNumAlphasGasCoolera(0);         // Maximum number of alphas for air-cooled gas cooler object
    int MaxNumAlphasComp(0);               // Maximum number of alphas for compressor object
    int MaxNumAlphasCompressorList(0);     // Maximum number of alphas for compressor list objects
    int MaxNumAlphasCase(0);               // Maximum number of alphas for case object
    int MaxNumAlphasCaseAndWalkInList(0);  // Maximum number of alphas in CaseAndWalkInList
    int MaxNumAlphasWalkIn(0);             // Maximum number of alphas for walkin object
    int MaxNumAlphasSecond(0);             // Maximum number of alphas for air chiller object
    int MaxNumNumbersAirChiller(0);        // Maximum number of numbers for air chiller object
    int MaxNumNumbersSecond(0);            // Maximum number of numbers for secondary system object
    int MaxNumNumbersWalkIn(0);            // Maximum number of numbers for walkin object
    int MaxNumNumbersCase(0);              // Maximum number of numbers for case object
    int MaxNumNumbersCaseAndWalkInList(0); // Maximum number of numbers in CaseAndWalkInList
    int MaxNumNumbersRack(0);              // Maximum number of numbers for rack object
    int MaxNumNumbersAll(0);               // Maximum number of numeric inputs for all objects
    int MaxNumNumbersSys(0);               // Maximum number of numbers for system object
    int MaxNumNumbersTransSys(0);          // Maximum number of numbers for transcritical system object
    int MaxNumNumbersChillerSet(0);        // Maximum number of numbers for chiller set object
    int MaxNumNumbersConda(0);             // Maximum number of numbers for air-cooled condenser object
    int MaxNumNumbersConde(0);             // Maximum number of numbers for evap-cooled condenser object
    int MaxNumNumbersCondw(0);             // Maximum number of numbers for water-cooled condenser object
    int MaxNumNumbersGasCoolera(0);        // Maximum number of numbers for air-cooled gas cooler object
    int MaxNumNumbersComp(0);              // Maximum number of numbers for compressor object
    int MaxNumNumbersCompressorList(0);    // Maximum number of numbers
    int MaxNumArgs(0);                     // Max number of alphas and numbers (arguments) for rack object
    int NumAlphas(0);                      // Number of Alphas for each GetObjectItem call
    int NumCases(0);                       // Number of refrigerated cases for single system
    int NumNum(0);                         // Used to cycle through input
    int NumNumbers(0);                     // Number of Numbers for each GetObjectItem call
    int NumDisplayCases(0);                // Counter for refrigerated cases in GetInput do loop
    int NumWalkIns(0);                     // Number of walk ins
    int RefrigSysNum(0);
    Real64 DeltaHPhaseChange(0.0);     // Secondary loop enthalpy change in condenser w overfeed system (J/g)
    Real64 DelTempMin(0.0);            // min temperature for heat rej curve for air cooled condenser (C)
    Real64 DelTempMax(0.0);            // max temperature for heat rej curve for air cooled condenser (C)
    Real64 DensityBrineRated(0.0);     // density of circ fluid in secondary loop
    Real64 DensityPhaseChange(0.0);    // Secondary loop density at condensing temperature w overfeed system (g/m3)
    Real64 NominalTotalCompCapLP(0.0); // Total of nominal low pressure compressor capacities, used for rough input check (W) (Transcritical CO2)
    Real64 NominalTotalCompCapHP(0.0);
    Array1D<Real64> Numbers;   // Numeric items for object
    Array2D<Real64> DayValues; // Array of schedule values

    auto &RefrigCase = state.dataRefrigCase->RefrigCase;
    auto &RefrigRack = state.dataRefrigCase->RefrigRack;
    auto &CaseRAFraction = state.dataRefrigCase->CaseRAFraction;
    auto &System = state.dataRefrigCase->System;
    auto &TransSystem = state.dataRefrigCase->TransSystem;
    auto &Condenser = state.dataRefrigCase->Condenser;
    auto &Compressor = state.dataRefrigCase->Compressor;
    auto &GasCooler = state.dataRefrigCase->GasCooler;
    auto &Subcooler = state.dataRefrigCase->Subcooler;
    auto &CaseAndWalkInList = state.dataRefrigCase->CaseAndWalkInList;
    auto &CompressorLists = state.dataRefrigCase->CompressorLists;
    auto &Secondary = state.dataRefrigCase->Secondary;
    auto &TransferLoadList = state.dataRefrigCase->TransferLoadList;
    auto &WalkIn = state.dataRefrigCase->WalkIn;
    auto &WarehouseCoil = state.dataRefrigCase->WarehouseCoil;
    auto &AirChillerSet = state.dataRefrigCase->AirChillerSet;
    auto &CoilSysCredit = state.dataRefrigCase->CoilSysCredit;
    auto &CaseWIZoneReport = state.dataRefrigCase->CaseWIZoneReport;

    state.dataRefrigCase->NumSimulationCascadeCondensers =
        state.dataInputProcessing->inputProcessor->getNumObjectsFound(state, "Refrigeration:Condenser:Cascade");
    state.dataRefrigCase->NumSimulationCases = state.dataInputProcessing->inputProcessor->getNumObjectsFound(state, "Refrigeration:Case");
    state.dataRefrigCase->NumSimulationCaseAndWalkInLists =
        state.dataInputProcessing->inputProcessor->getNumObjectsFound(state, "Refrigeration:CaseAndWalkInList");
    state.dataRefrigCase->NumRefrigeratedRacks = state.dataInputProcessing->inputProcessor->getNumObjectsFound(state, "Refrigeration:CompressorRack");
    state.dataRefrigCase->NumSimulationSecondarySystems =
        state.dataInputProcessing->inputProcessor->getNumObjectsFound(state, "Refrigeration:SecondarySystem");
    state.dataRefrigCase->NumSimulationTransferLoadLists =
        state.dataInputProcessing->inputProcessor->getNumObjectsFound(state, "Refrigeration:TransferLoadList");
    state.dataRefrigCase->NumSimulationWalkIns = state.dataInputProcessing->inputProcessor->getNumObjectsFound(state, "Refrigeration:WalkIn");
    state.dataRefrigCase->NumRefrigSystems = state.dataInputProcessing->inputProcessor->getNumObjectsFound(state, "Refrigeration:System");
    state.dataRefrigCase->NumTransRefrigSystems =
        state.dataInputProcessing->inputProcessor->getNumObjectsFound(state, "Refrigeration:TranscriticalSystem");
    state.dataRefrigCase->NumSimulationCondAir =
        state.dataInputProcessing->inputProcessor->getNumObjectsFound(state, "Refrigeration:Condenser:AirCooled");
    state.dataRefrigCase->NumSimulationCondEvap =
        state.dataInputProcessing->inputProcessor->getNumObjectsFound(state, "Refrigeration:Condenser:EvaporativeCooled");
    state.dataRefrigCase->NumSimulationCondWater =
        state.dataInputProcessing->inputProcessor->getNumObjectsFound(state, "Refrigeration:Condenser:WaterCooled");
    state.dataRefrigCase->NumSimulationGasCooler =
        state.dataInputProcessing->inputProcessor->getNumObjectsFound(state, "Refrigeration:GasCooler:AirCooled");
    state.dataRefrigCase->NumRefrigCondensers = state.dataRefrigCase->NumSimulationCondAir + state.dataRefrigCase->NumSimulationCondEvap +
                                                state.dataRefrigCase->NumSimulationCondWater + state.dataRefrigCase->NumSimulationCascadeCondensers;
    state.dataRefrigCase->NumSimulationCompressors = state.dataInputProcessing->inputProcessor->getNumObjectsFound(state, "Refrigeration:Compressor");
    state.dataRefrigCase->NumSimulationSubcoolers = state.dataInputProcessing->inputProcessor->getNumObjectsFound(state, "Refrigeration:Subcooler");
    int NumCompressorLists = state.dataInputProcessing->inputProcessor->getNumObjectsFound(state, "Refrigeration:CompressorList");
    state.dataRefrigCase->NumRefrigChillerSets =
        state.dataInputProcessing->inputProcessor->getNumObjectsFound(state, "ZoneHVAC:RefrigerationChillerSet");
    state.dataRefrigCase->NumSimulationRefrigAirChillers =
        state.dataInputProcessing->inputProcessor->getNumObjectsFound(state, "Refrigeration:AirChiller");

    // Set flags used later to avoid unnecessary steps.
    if (state.dataRefrigCase->NumRefrigeratedRacks == 0) {
        state.dataRefrigCase->HaveRefrigRacks = false;
    }
    if (state.dataRefrigCase->NumRefrigSystems == 0) {
        state.dataRefrigCase->HaveDetailedRefrig = false;
    }
    if (state.dataRefrigCase->NumTransRefrigSystems == 0) {
        state.dataRefrigCase->HaveDetailedTransRefrig = false;
    }
    if (state.dataRefrigCase->NumSimulationCases == 0 && state.dataRefrigCase->NumSimulationWalkIns == 0) {
        state.dataRefrigCase->HaveCasesOrWalkins = false;
    }
    if (state.dataRefrigCase->NumSimulationRefrigAirChillers == 0) {
        state.dataRefrigCase->HaveChillers = false;
    }

    if (state.dataRefrigCase->NumRefrigeratedRacks > 0) {
        RefrigRack.allocate(state.dataRefrigCase->NumRefrigeratedRacks);
        state.dataHeatBal->HeatReclaimRefrigeratedRack.allocate(state.dataRefrigCase->NumRefrigeratedRacks);
    }
    if (state.dataRefrigCase->NumRefrigSystems > 0) {
        System.allocate(state.dataRefrigCase->NumRefrigSystems);
        state.dataRefrigCase->ShowUnmetEnergyWarning.allocate(state.dataRefrigCase->NumRefrigSystems);
        state.dataRefrigCase->ShowHiStageUnmetEnergyWarning.allocate(state.dataRefrigCase->NumRefrigSystems);
        state.dataRefrigCase->ShowUnmetEnergyWarning = true;
        state.dataRefrigCase->ShowHiStageUnmetEnergyWarning = true;
    }
    if (state.dataRefrigCase->NumTransRefrigSystems > 0) {
        TransSystem.allocate(state.dataRefrigCase->NumTransRefrigSystems);
        state.dataRefrigCase->ShowUnmetEnergyWarningTrans.dimension(state.dataRefrigCase->NumTransRefrigSystems, true);
    }
    if (state.dataRefrigCase->NumRefrigChillerSets > 0) {
        AirChillerSet.allocate(state.dataRefrigCase->NumRefrigChillerSets);
    }
    if (state.dataRefrigCase->NumRefrigCondensers > 0) {
        state.dataHeatBal->HeatReclaimRefrigCondenser.allocate(state.dataRefrigCase->NumRefrigCondensers);
        Condenser.allocate(state.dataRefrigCase->NumRefrigCondensers);
        state.dataRefrigCase->UniqueCondenserNames.reserve(static_cast<unsigned>(state.dataRefrigCase->NumRefrigCondensers));
    }
    if (state.dataRefrigCase->NumSimulationGasCooler > 0) {
        GasCooler.allocate(state.dataRefrigCase->NumSimulationGasCooler);
    }
    if (state.dataRefrigCase->NumSimulationCases > 0) {
        CaseRAFraction.allocate(state.dataGlobal->NumOfZones);
        RefrigCase.allocate(state.dataRefrigCase->NumSimulationCases);
    }
    if (state.dataRefrigCase->NumSimulationWalkIns > 0) {
        WalkIn.allocate(state.dataRefrigCase->NumSimulationWalkIns);
    }
    if ((state.dataRefrigCase->NumSimulationWalkIns > 0) || (state.dataRefrigCase->NumSimulationCases > 0)) {
        CaseWIZoneReport.allocate(state.dataGlobal->NumOfZones);
    } else {
        state.dataRefrigCase->UseSysTimeStep = true;
        // needed to avoid accessing unallocated caseWIZoneReport on early call to SumZones
    }
    if (state.dataRefrigCase->NumSimulationSecondarySystems > 0) {
        Secondary.allocate(state.dataRefrigCase->NumSimulationSecondarySystems);
        state.dataRefrigCase->ShowUnmetSecondEnergyWarning.dimension(state.dataRefrigCase->NumSimulationSecondarySystems, true);
    }
    if (state.dataRefrigCase->NumSimulationRefrigAirChillers > 0) {
        WarehouseCoil.allocate(state.dataRefrigCase->NumSimulationRefrigAirChillers);
        CoilSysCredit.allocate(state.dataGlobal->NumOfZones);
    }
    if (state.dataRefrigCase->NumSimulationCompressors > 0) {
        Compressor.allocate(state.dataRefrigCase->NumSimulationCompressors);
    }
    if (state.dataRefrigCase->NumSimulationSubcoolers > 0) {
        Subcooler.allocate(state.dataRefrigCase->NumSimulationSubcoolers);
    }
    if (state.dataRefrigCase->NumSimulationCaseAndWalkInLists > 0) {
        CaseAndWalkInList.allocate(state.dataRefrigCase->NumSimulationCaseAndWalkInLists);
    }
    if (NumCompressorLists > 0) {
        CompressorLists.allocate(NumCompressorLists);
    }
    if (state.dataRefrigCase->NumSimulationTransferLoadLists > 0) {
        TransferLoadList.allocate(state.dataRefrigCase->NumSimulationTransferLoadLists);
    }

    DayValues.allocate(state.dataGlobal->TimeStepsInHour, Constant::iHoursInDay);
    state.dataRefrigCase->RefrigPresentInZone.dimension(state.dataGlobal->NumOfZones, false);

    state.dataInputProcessing->inputProcessor->getObjectDefMaxArgs(state, "Refrigeration:Case", MaxNumArgs, MaxNumAlphasCase, MaxNumNumbersCase);
    state.dataInputProcessing->inputProcessor->getObjectDefMaxArgs(
        state, "Refrigeration:CaseAndWalkInList", MaxNumArgs, MaxNumAlphasCaseAndWalkInList, MaxNumNumbersCaseAndWalkInList);
    state.dataInputProcessing->inputProcessor->getObjectDefMaxArgs(
        state, "Refrigeration:CompressorRack", MaxNumArgs, MaxNumAlphasRack, MaxNumNumbersRack);
    state.dataInputProcessing->inputProcessor->getObjectDefMaxArgs(state, "Refrigeration:System", MaxNumArgs, MaxNumAlphasSys, MaxNumNumbersSys);
    state.dataInputProcessing->inputProcessor->getObjectDefMaxArgs(
        state, "Refrigeration:TranscriticalSystem", MaxNumArgs, MaxNumAlphasTransSys, MaxNumNumbersTransSys);
    state.dataInputProcessing->inputProcessor->getObjectDefMaxArgs(
        state, "Refrigeration:Condenser:AirCooled", MaxNumArgs, MaxNumAlphasConda, MaxNumNumbersConda);
    state.dataInputProcessing->inputProcessor->getObjectDefMaxArgs(
        state, "Refrigeration:Condenser:EvaporativeCooled", MaxNumArgs, MaxNumAlphasConde, MaxNumNumbersConde);
    state.dataInputProcessing->inputProcessor->getObjectDefMaxArgs(
        state, "Refrigeration:Condenser:WaterCooled", MaxNumArgs, MaxNumAlphasCondw, MaxNumNumbersCondw);
    state.dataInputProcessing->inputProcessor->getObjectDefMaxArgs(
        state, "Refrigeration:GasCooler:AirCooled", MaxNumArgs, MaxNumAlphasGasCoolera, MaxNumNumbersGasCoolera);
    state.dataInputProcessing->inputProcessor->getObjectDefMaxArgs(
        state, "Refrigeration:Compressor", MaxNumArgs, MaxNumAlphasComp, MaxNumNumbersComp);
    state.dataInputProcessing->inputProcessor->getObjectDefMaxArgs(
        state, "Refrigeration:CompressorList", MaxNumArgs, MaxNumAlphasCompressorList, MaxNumNumbersCompressorList);
    state.dataInputProcessing->inputProcessor->getObjectDefMaxArgs(
        state, "Refrigeration:WalkIn", MaxNumArgs, MaxNumAlphasWalkIn, MaxNumNumbersWalkIn);
    state.dataInputProcessing->inputProcessor->getObjectDefMaxArgs(
        state, "Refrigeration:SecondarySystem", MaxNumArgs, MaxNumAlphasSecond, MaxNumNumbersSecond);
    state.dataInputProcessing->inputProcessor->getObjectDefMaxArgs(
        state, "ZoneHVAC:RefrigerationChillerSet", MaxNumArgs, MaxNumAlphasChillerSet, MaxNumNumbersChillerSet);
    state.dataInputProcessing->inputProcessor->getObjectDefMaxArgs(
        state, "Refrigeration:AirChiller", MaxNumArgs, MaxNumAlphasAirChiller, MaxNumNumbersAirChiller);

    MaxNumAlphasAll = max(MaxNumAlphasCase,
                          MaxNumAlphasCaseAndWalkInList,
                          MaxNumAlphasRack,
                          MaxNumAlphasSys,
                          MaxNumAlphasTransSys,
                          MaxNumAlphasConda,
                          MaxNumAlphasConde,
                          MaxNumAlphasCondw,
                          MaxNumAlphasGasCoolera,
                          MaxNumAlphasComp,
                          MaxNumAlphasCompressorList,
                          MaxNumAlphasSecond,
                          MaxNumAlphasWalkIn,
                          MaxNumAlphasChillerSet,
                          MaxNumAlphasAirChiller);
    MaxNumNumbersAll = max(MaxNumNumbersCase,
                           MaxNumNumbersCaseAndWalkInList,
                           MaxNumNumbersRack,
                           MaxNumNumbersSys,
                           MaxNumNumbersTransSys,
                           MaxNumNumbersConda,
                           MaxNumNumbersConde,
                           MaxNumNumbersCondw,
                           MaxNumNumbersGasCoolera,
                           MaxNumNumbersComp,
                           MaxNumNumbersCompressorList,
                           MaxNumNumbersSecond,
                           MaxNumNumbersWalkIn,
                           MaxNumNumbersChillerSet,
                           MaxNumNumbersAirChiller);

    Alphas.allocate(MaxNumAlphasAll);
    Numbers.dimension(MaxNumNumbersAll, 0.0);
    cAlphaFieldNames.allocate(MaxNumAlphasAll);
    cNumericFieldNames.allocate(MaxNumNumbersAll);
    lAlphaBlanks.dimension(MaxNumAlphasAll, true);
    lNumericBlanks.dimension(MaxNumNumbersAll, true);
    // bbb stovall note for future - for all curve entries, see if need fail on type or if can allow table input
    if (state.dataRefrigCase->NumSimulationCases > 0) {
        CurrentModuleObject = "Refrigeration:Case";
        for (int CaseNum = 1; CaseNum <= state.dataRefrigCase->NumSimulationCases; ++CaseNum) {
            state.dataInputProcessing->inputProcessor->getObjectItem(state,
                                                                     CurrentModuleObject,
                                                                     CaseNum,
                                                                     Alphas,
                                                                     NumAlphas,
                                                                     Numbers,
                                                                     NumNumbers,
                                                                     IOStatus,
                                                                     lNumericBlanks,
                                                                     lAlphaBlanks,
                                                                     cAlphaFieldNames,
                                                                     cNumericFieldNames);

            ErrorObjectHeader eoh{routineName, CurrentModuleObject, Alphas(1)};

            ++NumDisplayCases;

            AlphaNum = 1;
            Util::IsNameEmpty(state, Alphas(1), CurrentModuleObject, ErrorsFound);
            RefrigCase(CaseNum).Name = Alphas(AlphaNum);

            AlphaNum = 2;
            if (lAlphaBlanks(AlphaNum)) {
                RefrigCase(CaseNum).availSched = Sched::GetScheduleAlwaysOn(state);
            } else if ((RefrigCase(CaseNum).availSched = Sched::GetSchedule(state, Alphas(AlphaNum))) == nullptr) {
                ShowSevereItemNotFound(state, eoh, cAlphaFieldNames(AlphaNum), Alphas(AlphaNum));
                ErrorsFound = true;
            } else if (!RefrigCase(CaseNum).availSched->checkMinMaxVals(state, Clusive::In, 0.0, Clusive::In, 1.0)) {
                Sched::ShowSevereBadMinMax(state, eoh, cAlphaFieldNames(AlphaNum), Alphas(AlphaNum), Clusive::In, 0.0, Clusive::In, 1.0);
                ErrorsFound = true;
            }

            // Get the Zone node number from the zone name entered by the user
            RefrigCase(CaseNum).ZoneName = Alphas(3);
            RefrigCase(CaseNum).ActualZoneNum = Util::FindItemInList(Alphas(3), state.dataHeatBal->Zone);

            if (RefrigCase(CaseNum).ActualZoneNum == 0) {
                ShowSevereError(state,
                                format("{}{}=\"{}\", invalid  {} not valid: {}",
                                       RoutineName,
                                       CurrentModuleObject,
                                       RefrigCase(CaseNum).Name,
                                       cAlphaFieldNames(3),
                                       Alphas(3)));
                ErrorsFound = true;
            } else {
                state.dataRefrigCase->RefrigPresentInZone(RefrigCase(CaseNum).ActualZoneNum) = true;
            }

            RefrigCase(CaseNum).ZoneNodeNum = DataZoneEquipment::GetSystemNodeNumberForZone(state, RefrigCase(CaseNum).ActualZoneNum);

            RefrigCase(CaseNum).RatedAmbientTemp = Numbers(1);
            if (Numbers(1) <= 0.0) {
                ShowSevereError(state,
                                format("{}{}=\"{}\", {} must be greater than 0 C",
                                       RoutineName,
                                       CurrentModuleObject,
                                       RefrigCase(CaseNum).Name,
                                       cNumericFieldNames(1)));
                ErrorsFound = true;
            }

            RefrigCase(CaseNum).RatedAmbientRH = Numbers(2);
            if (Numbers(2) <= 0.0 || Numbers(2) >= 100.0) {
                ShowSevereError(state,
                                format("{}{}=\"{}\", {} must be greater than 0% and less than 100%",
                                       RoutineName,
                                       CurrentModuleObject,
                                       RefrigCase(CaseNum).Name,
                                       cNumericFieldNames(2)));
                ErrorsFound = true;
            }
            RefrigCase(CaseNum).RatedAmbientDewPoint = Psychrometrics::PsyTdpFnWPb(
                state,
                Psychrometrics::PsyWFnTdbRhPb(
                    state, RefrigCase(CaseNum).RatedAmbientTemp, (RefrigCase(CaseNum).RatedAmbientRH / 100.0), state.dataEnvrn->StdBaroPress),
                state.dataEnvrn->StdBaroPress);

            RefrigCase(CaseNum).RateTotCapPerLength = Numbers(3);
            if (Numbers(3) <= 0.0) {
                ShowSevereError(state,
                                format("{}{}=\"{}\", {} must be greater than 0 W/m",
                                       RoutineName,
                                       CurrentModuleObject,
                                       RefrigCase(CaseNum).Name,
                                       cNumericFieldNames(3)));
                ErrorsFound = true;
            }

            RefrigCase(CaseNum).RatedLHR = Numbers(4);
            if (Numbers(4) < 0.0 || Numbers(4) > 1.0) {
                ShowSevereError(
                    state,
                    format(
                        "{}{}=\"{}\", {} must be >= 0 and <= 1", RoutineName, CurrentModuleObject, RefrigCase(CaseNum).Name, cNumericFieldNames(4)));
                ErrorsFound = true;
            }

            RefrigCase(CaseNum).RatedRTF = Numbers(5);
            if (Numbers(5) <= 0.0 || Numbers(5) > 1.0) {
                ShowSevereError(state,
                                format("{}{}=\"{}\", {} must be > 0 and <= to 1",
                                       RoutineName,
                                       CurrentModuleObject,
                                       RefrigCase(CaseNum).Name,
                                       cNumericFieldNames(5)));
                ErrorsFound = true;
            }

            RefrigCase(CaseNum).Length = Numbers(6);
            if (Numbers(6) <= 0.0) {
                ShowSevereError(state,
                                format("{}{}=\"{}\", {} must be greater than 0 m",
                                       RoutineName,
                                       CurrentModuleObject,
                                       RefrigCase(CaseNum).Name,
                                       cNumericFieldNames(6)));
                ErrorsFound = true;
            }

            RefrigCase(CaseNum).Temperature = Numbers(7);
            if (RefrigCase(CaseNum).Temperature >= RefrigCase(CaseNum).RatedAmbientTemp) {
                ShowSevereError(state,
                                format("{}{}=\"{}\", {} must be below {}",
                                       RoutineName,
                                       CurrentModuleObject,
                                       RefrigCase(CaseNum).Name,
                                       cNumericFieldNames(7),
                                       cNumericFieldNames(1)));
                ErrorsFound = true;
            }

            RefrigCase(CaseNum).LatentEnergyCurveType = static_cast<EnergyEqnForm>(getEnumValue(energyEqnFormNamesUC, Alphas(4)));
            if (RefrigCase(CaseNum).LatentEnergyCurveType == EnergyEqnForm::Invalid) {
                ShowSevereInvalidKey(state, eoh, cAlphaFieldNames(4), Alphas(4));
                ErrorsFound = true;
            }

            RefrigCase(CaseNum).LatCapCurvePtr = Curve::GetCurveIndex(state, Alphas(5)); // convert curve name to number
            if (RefrigCase(CaseNum).LatCapCurvePtr == 0) {
                ShowSevereItemNotFound(state, eoh, cAlphaFieldNames(5), Alphas(5));
                ErrorsFound = true;
            }

            ErrorsFound |= Curve::CheckCurveDims(state,
                                                 RefrigCase(CaseNum).LatCapCurvePtr, // Curve index
                                                 {1},                                // Valid dimensions
                                                 RoutineName,                        // Routine name
                                                 CurrentModuleObject,                // Object Type
                                                 RefrigCase(CaseNum).Name,           // Object Name
                                                 cAlphaFieldNames(5));               // Field Name

            NumNum = 8;
            if (!lNumericBlanks(NumNum)) {
                RefrigCase(CaseNum).STDFanPower = Numbers(NumNum);
                if (Numbers(NumNum) < 0.0) {
                    ShowSevereError(state,
                                    format("{}{}=\"{}\", {} must be greater than or equal to 0 W/m",
                                           RoutineName,
                                           CurrentModuleObject,
                                           RefrigCase(CaseNum).Name,
                                           cNumericFieldNames(NumNum)));
                    ErrorsFound = true;
                }
            } else { // blank use default of 75 W/m
                RefrigCase(CaseNum).STDFanPower = 75.0;
            } // blank input

            NumNum = 9;
            if (!lNumericBlanks(NumNum)) {
                RefrigCase(CaseNum).OperatingFanPower = Numbers(NumNum);
                if (Numbers(NumNum) < 0.0) {
                    ShowSevereError(state,
                                    format("{}{}=\"{}\", {} must be greater than or equal to 0 W/m",
                                           RoutineName,
                                           CurrentModuleObject,
                                           RefrigCase(CaseNum).Name,
                                           cNumericFieldNames(NumNum)));
                    ErrorsFound = true;
                }
            } else { // if blank set = to std fan power
                RefrigCase(CaseNum).OperatingFanPower = RefrigCase(CaseNum).STDFanPower;
            } // if blank

            NumNum = 10;
            if (!lNumericBlanks(NumNum)) {
                RefrigCase(CaseNum).RatedLightingPower = Numbers(NumNum);
                if (Numbers(NumNum) < 0.0) {
                    ShowSevereError(state,
                                    format("{}{}=\"{}\", {} must be greater than or equal to 0 W/m",
                                           RoutineName,
                                           CurrentModuleObject,
                                           RefrigCase(CaseNum).Name,
                                           cNumericFieldNames(NumNum)));
                    ErrorsFound = true;
                }
            } else { // blank input - use default of 90 W/m
                RefrigCase(CaseNum).RatedLightingPower = 90.0;
            } // blank input

            NumNum = 11;
            if (!lNumericBlanks(NumNum)) {
                RefrigCase(CaseNum).LightingPower = Numbers(NumNum);
                if (Numbers(NumNum) < 0.0) {
                    ShowSevereError(state,
                                    format("{}{}=\"{}\", {} must be greater than or equal to 0 W/m",
                                           RoutineName,
                                           CurrentModuleObject,
                                           RefrigCase(CaseNum).Name,
                                           cNumericFieldNames(NumNum)));
                    ErrorsFound = true;
                }
            } else { // blank input so set lighting power equal to rated/std lighting power
                RefrigCase(CaseNum).LightingPower = RefrigCase(CaseNum).RatedLightingPower;
            } // blank input

            if (lAlphaBlanks(6)) {
                RefrigCase(CaseNum).lightingSched = Sched::GetScheduleAlwaysOn(state); // Not an availability schedule, but defaults to constant-1.0
            } else if ((RefrigCase(CaseNum).lightingSched = Sched::GetSchedule(state, Alphas(6))) == nullptr) {
                ShowSevereItemNotFound(state, eoh, cAlphaFieldNames(6), Alphas(6));
                ErrorsFound = true;
            } else if (!RefrigCase(CaseNum).lightingSched->checkMinMaxVals(state, Clusive::In, 0.0, Clusive::In, 1.0)) {
                Sched::ShowSevereBadMinMax(state, eoh, cAlphaFieldNames(6), Alphas(6), Clusive::In, 0.0, Clusive::In, 1.0);
                ErrorsFound = true;
            }

            NumNum = 12;
            RefrigCase(CaseNum).LightingFractionToCase = 1.0; // default value
            if (!lNumericBlanks(NumNum)) {
                RefrigCase(CaseNum).LightingFractionToCase = Numbers(NumNum);
            } // blank input lighting fraction to case
            //   check lighting fraction to case input
            if (RefrigCase(CaseNum).LightingFractionToCase < 0.0 || RefrigCase(CaseNum).LightingFractionToCase > 1.0) {
                ShowSevereError(state,
                                format("{}{}=\"{}\", {} has a value outside the valid range",
                                       RoutineName,
                                       CurrentModuleObject,
                                       RefrigCase(CaseNum).Name,
                                       cNumericFieldNames(NumNum)));
                ShowContinueError(state, "  Minimum should be >= 0.0 and Maximum should be <= 1.0");
                ErrorsFound = true;
            }

            NumNum = 13;
            RefrigCase(CaseNum).AntiSweatPower = Numbers(NumNum);
            if (Numbers(NumNum) < 0.0) {
                ShowSevereError(state,
                                format("{}{}=\"{}\", {} must be greater than or equal to 0 W/m",
                                       RoutineName,
                                       CurrentModuleObject,
                                       RefrigCase(CaseNum).Name,
                                       cNumericFieldNames(NumNum)));
                ErrorsFound = true;
            }

            NumNum = 14;
            RefrigCase(CaseNum).MinimumASPower = Numbers(NumNum);
            if (Numbers(NumNum) < 0.0) {
                ShowSevereError(state,
                                format("{}{}=\"{}\", {} must be greater than or equal to 0 W/m",
                                       RoutineName,
                                       CurrentModuleObject,
                                       RefrigCase(CaseNum).Name,
                                       cNumericFieldNames(NumNum)));
                ErrorsFound = true;
            }

            RefrigCase(CaseNum).AntiSweatControlType = static_cast<ASHtrCtrlType>(getEnumValue(asHtrCtrlTypeNamesUC, Alphas(7)));
            if (RefrigCase(CaseNum).AntiSweatControlType == ASHtrCtrlType::Invalid) {
                ShowSevereInvalidKey(state, eoh, cAlphaFieldNames(7), Alphas(7));
                ErrorsFound = true;
            } else if (RefrigCase(CaseNum).AntiSweatControlType == ASHtrCtrlType::None) {
                RefrigCase(CaseNum).AntiSweatPower = 0.0;
            }

            //   Assure that case temperature is below the rated dew point when anti-sweat heater control type is dew point method
            if (RefrigCase(CaseNum).Temperature >= RefrigCase(CaseNum).RatedAmbientDewPoint &&
                RefrigCase(CaseNum).AntiSweatControlType == ASHtrCtrlType::DewPoint) {
                ShowSevereError(state,
                                format("{}{}=\"{}\", {} must be below the Rated Ambient Dew Point when {} is Dew Point Method",
                                       RoutineName,
                                       CurrentModuleObject,
                                       RefrigCase(CaseNum).Name,
                                       cNumericFieldNames(7),
                                       cAlphaFieldNames(7)));
                ErrorsFound = true;
            }

            NumNum = 15;
            //  negative values for minimum humidity are allowed
            RefrigCase(CaseNum).HumAtZeroAS = Numbers(NumNum);

            //   check minimum humidity when linear AS control type is used
            if (RefrigCase(CaseNum).HumAtZeroAS >= RefrigCase(CaseNum).RatedAmbientRH &&
                RefrigCase(CaseNum).AntiSweatControlType == ASHtrCtrlType::Linear) {
                ShowSevereError(state,
                                format("{}{}=\"{}\", {} must be less than {}",
                                       RoutineName,
                                       CurrentModuleObject,
                                       RefrigCase(CaseNum).Name,
                                       cNumericFieldNames(NumNum),
                                       cNumericFieldNames(2)));
                ShowContinueError(state, format(" for Linear {}.", cAlphaFieldNames(7)));
                ErrorsFound = true;
            }

            NumNum = 16;
            RefrigCase(CaseNum).Height = Numbers(NumNum);
            if (Numbers(NumNum) < 0.0) {
                ShowSevereError(state,
                                format("{}{}=\"{}\", {} must be greater than or equal to 0 m",
                                       RoutineName,
                                       CurrentModuleObject,
                                       RefrigCase(CaseNum).Name,
                                       cNumericFieldNames(NumNum)));
                ErrorsFound = true;
            }

            if (RefrigCase(CaseNum).Height <= 0.0 && RefrigCase(CaseNum).AntiSweatControlType == ASHtrCtrlType::HeatBalance) {
                ShowSevereError(state,
                                format("{}{}=\"{}\", {} must be greater than 0 when {} is Heat Balance Method.",
                                       RoutineName,
                                       CurrentModuleObject,
                                       RefrigCase(CaseNum).Name,
                                       cNumericFieldNames(NumNum),
                                       cAlphaFieldNames(7)));
                ShowContinueError(state, format("..given {} was: {:.3R}", cNumericFieldNames(NumNum), RefrigCase(CaseNum).Height));
                ErrorsFound = true;
            }

            //   initialize case resistance for anti-sweat heater control type = Heat Balance Method
            if (RefrigCase(CaseNum).AntiSweatControlType == ASHtrCtrlType::HeatBalance) {
                Real64 Rcase(0.0);      // Case thermal resistance used with anti-sweat heater control
                Real64 RcaseDenom(0.0); // Denominator of case thermal resistance calculation for anti-sweat

                if (RefrigCase(CaseNum).Height == 0.0) {
                    Rcase = 0.0;
                } else {
                    RcaseDenom = ((RefrigCase(CaseNum).AntiSweatPower / RefrigCase(CaseNum).Height) -
                                  (RefrigCase(CaseNum).RatedAmbientDewPoint - RefrigCase(CaseNum).RatedAmbientTemp) / Rair);
                    Rcase = (RefrigCase(CaseNum).RatedAmbientDewPoint - RefrigCase(CaseNum).Temperature) / RcaseDenom;
                }
                RefrigCase(CaseNum).Rcase = max(0.0, Rcase);
                if (RefrigCase(CaseNum).Rcase == 0.0) {
                    ShowWarningError(state,
                                     format("{}=\"{}\" A case thermal resistance of 0 was calculated for anti-sweat heater performance using the",
                                            CurrentModuleObject,
                                            RefrigCase(CaseNum).Name));
                    ShowContinueError(state,
                                      format(" Heat Balance Method control type. Anti-sweat heater performance cannot be calculated and {} will be "
                                             "set to None and simulation continues.",
                                             cAlphaFieldNames(7)));
                    ShowContinueError(state, " See Engineering Documentation for anti-sweat heater control of refrigerated cases.");
                }
            }

            NumNum = 17;
            RefrigCase(CaseNum).ASHeaterFractionToCase = Numbers(NumNum);
            if (Numbers(NumNum) < 0.0 || Numbers(NumNum) > 1.0) {
                ShowSevereError(state,
                                format("{}{}=\"{}\", {} must be >= 0 and <= 1",
                                       RoutineName,
                                       CurrentModuleObject,
                                       RefrigCase(CaseNum).Name,
                                       cNumericFieldNames(NumNum)));
                ErrorsFound = true;
            }

            // Multiple strings mapping to the same enum is not good
            if (Alphas(8) == "HOTGAS") {
                Alphas(8) = "HOTFLUID";
            } else if (Alphas(8) == "HOTGASWITHTEMPERATURETERMINATION") {
                Alphas(8) = "HOTFLUIDWITHTEMPERATURETERMINATION";
            }

            RefrigCase(CaseNum).defrostType = static_cast<RefCaseDefrostType>(getEnumValue(refCaseDefrostTypeNamesUC, Alphas(8)));
            if (RefrigCase(CaseNum).defrostType == RefCaseDefrostType::Invalid) {
                ShowWarningInvalidKey(state, eoh, cAlphaFieldNames(8), Alphas(8), "None");
                RefrigCase(CaseNum).defrostType = RefCaseDefrostType::None;
            }

            RefCaseDefrostType DefType = RefrigCase(CaseNum).defrostType;
            NumNum = 18;
            if (!lNumericBlanks(NumNum)) {
                RefrigCase(CaseNum).DefrostPower = Numbers(NumNum);
                if (Numbers(NumNum) < 0.0) {
                    ShowSevereError(state,
                                    format("{}{}=\"{}\", {} must be greater than or equal to 0 W/m",
                                           RoutineName,
                                           CurrentModuleObject,
                                           RefrigCase(CaseNum).Name,
                                           cNumericFieldNames(NumNum)));
                    ErrorsFound = true;
                }
                //   disregard defrost power for Off-Cycle or None defrost types
                if ((DefType == RefCaseDefrostType::OffCycle || DefType == RefCaseDefrostType::None) && (RefrigCase(CaseNum).DefrostPower > 0.0)) {
                    RefrigCase(CaseNum).DefrostPower = 0.0;
                    ShowWarningError(state,
                                     format("{}=\"{}\", {} for {} None or Off-Cycle will be set to 0 and simulation continues.",
                                            CurrentModuleObject,
                                            RefrigCase(CaseNum).Name,
                                            cNumericFieldNames(NumNum),
                                            cAlphaFieldNames(8)));
                }
            } else {
                RefrigCase(CaseNum).DefrostPower = 0.0;
            }

            // defrost power needed to calculate heat gain to case even if not needed for electric consumption
            if ((DefType == RefCaseDefrostType::HotFluid || DefType == RefCaseDefrostType::HotFluidTerm || DefType == RefCaseDefrostType::Electric ||
                 DefType == RefCaseDefrostType::ElectricTerm) &&
                RefrigCase(CaseNum).DefrostPower <= 0.0) {
                ShowSevereError(state,
                                format("{}{}=\"{}\", {} must be greater than 0 W/m for {} {}",
                                       RoutineName,
                                       CurrentModuleObject,
                                       RefrigCase(CaseNum).Name,
                                       cNumericFieldNames(NumNum),
                                       cAlphaFieldNames(8),
                                       Alphas(8)));
                ErrorsFound = true;
            }

            if (RefrigCase(CaseNum).defrostType == RefCaseDefrostType::None) {
            } else if (lAlphaBlanks(9)) {
                ShowSevereEmptyField(state, eoh, cAlphaFieldNames(9));
                ErrorsFound = true;
            } else if ((RefrigCase(CaseNum).defrostSched = Sched::GetSchedule(state, Alphas(9))) == nullptr) {
                ShowSevereItemNotFound(state, eoh, cAlphaFieldNames(9), Alphas(9));
                ErrorsFound = true;
            } else if (!RefrigCase(CaseNum).defrostSched->checkMinMaxVals(state, Clusive::In, 0.0, Clusive::In, 1.0)) {
                Sched::ShowSevereBadMinMax(state, eoh, cAlphaFieldNames(9), Alphas(9), Clusive::In, 0.0, Clusive::In, 1.0);
                ErrorsFound = true;
            }

            //   Note that next section counting number cycles and setting maxkgfrost not used now, but may be in the future.
            //   count the number of defrost cycles

            // Flag for counting defrost cycles
            int NumDefCycles = 0;

            if (RefrigCase(CaseNum).defrostSched != nullptr) {
                bool StartCycle = false;
                std::vector<Real64> const &dayVals = RefrigCase(CaseNum).defrostSched->getDayVals(state, 1);
                for (int i = 0; i < Constant::iHoursInDay * state.dataGlobal->TimeStepsInHour; ++i) {
                    if (dayVals[i] == 0.0) {
                        StartCycle = false;
                    } else if (!StartCycle) {
                        ++NumDefCycles;
                        StartCycle = true;
                    }
                }
            }

            if (NumDefCycles > 0) {
                //     calculate maximum frost formation based on defrost schedule, heat of vaporization+fusion for water = 2833.0 kJ/kg
                RefrigCase(CaseNum).MaxKgFrost =
                    (RefrigCase(CaseNum).RateTotCapPerLength * RefrigCase(CaseNum).RatedLHR * RefrigCase(CaseNum).RatedRTF * Constant::rSecsInHour *
                     Constant::rHoursInDay / 1000.0 / 2833.0) / // Parenthesize!!!
                    (NumDefCycles);
            } else {
                RefrigCase(CaseNum).MaxKgFrost = 9999999.9;
            }

            //   some defrost types do not use drip-down schedules, use same defrost schedule pointer in that case
            if (lAlphaBlanks(10)) {
                RefrigCase(CaseNum).defrostDripDownSched = RefrigCase(CaseNum).defrostSched;
            } else if ((RefrigCase(CaseNum).defrostDripDownSched = Sched::GetSchedule(state, Alphas(10))) == nullptr) {
                ShowSevereItemNotFound(state, eoh, cAlphaFieldNames(10), Alphas(10));
                ErrorsFound = true;
            } else if (!RefrigCase(CaseNum).defrostDripDownSched->checkMinMaxVals(state, Clusive::In, 0.0, Clusive::In, 1.0)) {
                Sched::ShowSevereBadMinMax(state, eoh, cAlphaFieldNames(10), Alphas(10), Clusive::In, 0.0, Clusive::In, 1.0);
                ErrorsFound = true;
            }

            RefrigCase(CaseNum).DefrostEnergyCurveType = static_cast<EnergyEqnForm>(getEnumValue(energyEqnFormNamesUC, Alphas(11)));
            if (RefrigCase(CaseNum).DefrostEnergyCurveType == EnergyEqnForm::Invalid) {
                ShowSevereInvalidKey(state, eoh, cAlphaFieldNames(11), Alphas(11));
                ErrorsFound = true;
            }

            RefrigCase(CaseNum).DefCapCurvePtr = Curve::GetCurveIndex(state, Alphas(12)); // convert curve name to number
            if ((RefrigCase(CaseNum).defrostType == RefCaseDefrostType::ElectricTerm ||
                 RefrigCase(CaseNum).defrostType == RefCaseDefrostType::HotFluidTerm) &&
                (RefrigCase(CaseNum).DefCapCurvePtr == 0)) {
                ShowSevereItemNotFound(state, eoh, cAlphaFieldNames(12), Alphas(12));
                ErrorsFound = true;
            }

            if (RefrigCase(CaseNum).DefCapCurvePtr > 0) {
                ErrorsFound |= Curve::CheckCurveDims(state,
                                                     RefrigCase(CaseNum).DefCapCurvePtr, // Curve index
                                                     {1},                                // Valid dimensions
                                                     RoutineName,                        // Routine name
                                                     CurrentModuleObject,                // Object Type
                                                     RefrigCase(CaseNum).Name,           // Object Name
                                                     cAlphaFieldNames(12));              // Field Name
            }

            //  warn user if defrost energy curve is entered that it is only used for temperature termination types
            if (RefrigCase(CaseNum).DefCapCurvePtr > 0) {
                if (RefrigCase(CaseNum).defrostType != RefCaseDefrostType::ElectricTerm &&
                    RefrigCase(CaseNum).defrostType != RefCaseDefrostType::HotFluidTerm) {
                    ShowWarningError(state,
                                     format("{}=\"{}\", invalid  {} is only applicable to Defrost Temperature Termination types.",
                                            CurrentModuleObject,
                                            RefrigCase(CaseNum).Name,
                                            cAlphaFieldNames(12)));
                    ShowContinueError(state, format("{} will be disregarded and simulation continues.", cAlphaFieldNames(12)));
                }
            }

            NumNum = 19;
            RefrigCase(CaseNum).RAFrac = Numbers(NumNum);
            if (Numbers(NumNum) < 0.0 || Numbers(NumNum) > 1.0) {
                ShowSevereError(state,
                                format("{}{}=\"{}\", {} must be >= 0 or <= 1 ",
                                       RoutineName,
                                       CurrentModuleObject,
                                       RefrigCase(CaseNum).Name,
                                       cNumericFieldNames(NumNum)));
                ErrorsFound = true;
            }

            // Set return air node number
            RefrigCase(CaseNum).ZoneRANode = 0;
            std::string retNodeName;
            if (!lAlphaBlanks(15)) {
                retNodeName = Alphas(15);
            }
            if (RefrigCase(CaseNum).RAFrac > 0.0) {
                std::string callDescription = CurrentModuleObject + "=" + RefrigCase(CaseNum).Name;
                RefrigCase(CaseNum).ZoneRANode =
                    DataZoneEquipment::GetReturnAirNodeForZone(state, RefrigCase(CaseNum).ActualZoneNum, retNodeName, callDescription);
            }

            if (RefrigCase(CaseNum).ActualZoneNum >= 0) {
                if (RefrigCase(CaseNum).ZoneNodeNum == 0) {
                    ShowSevereError(state,
                                    format("{}{}=\"{}\", System Node Number not found for {} = {}",
                                           RoutineName,
                                           CurrentModuleObject,
                                           RefrigCase(CaseNum).Name,
                                           cAlphaFieldNames(3),
                                           Alphas(3)));
                    ShowContinueError(state,
                                      "..Refrigerated cases must reference a controlled Zone (appear in a ZoneHVAC:EquipmentConnections object).");
                    ErrorsFound = true;
                }
                if ((RefrigCase(CaseNum).RAFrac > 0.0) && (RefrigCase(CaseNum).ZoneRANode == 0)) {
                    ShowSevereError(state,
                                    format("{}{}=\"{}\", Under Case HVAC Return Air Node number not found for {} = {}",
                                           RoutineName,
                                           CurrentModuleObject,
                                           RefrigCase(CaseNum).Name,
                                           cAlphaFieldNames(3),
                                           Alphas(3)));
                    ShowContinueError(state,
                                      "..Refrigerated cases must reference a controlled Zone (appear in a ZoneHVAC:EquipmentConnections object) "
                                      "with at least one return air node.");
                    ErrorsFound = true;
                }
            }

            // set flag in Zone Data if RAFrac > 0
            if (RefrigCase(CaseNum).RAFrac > 0.0) {
                state.dataHeatBal->Zone(RefrigCase(CaseNum).ActualZoneNum).RefrigCaseRA = true;
            }

            //   Make sure RA node exists for display cases with under case HVAC returns
            if (RefrigCase(CaseNum).ZoneRANode == 0 && RefrigCase(CaseNum).RAFrac > 0.0) {
                ShowSevereError(state,
                                format("{}{}=\"{}\", {} not applicable to zones without return air systems.",
                                       RoutineName,
                                       CurrentModuleObject,
                                       RefrigCase(CaseNum).Name,
                                       cNumericFieldNames(19)));
                ErrorsFound = true;
            }

            if (RefrigCase(CaseNum).ActualZoneNum != 0) {
                CaseRAFraction(RefrigCase(CaseNum).ActualZoneNum).TotalCaseRAFraction += RefrigCase(CaseNum).RAFrac;
                CaseRAFraction(RefrigCase(CaseNum).ActualZoneNum).ZoneName = RefrigCase(CaseNum).ZoneName;
            }

            if (lAlphaBlanks(13)) {
            } else if ((RefrigCase(CaseNum).stockingSched = Sched::GetSchedule(state, Alphas(13))) == nullptr) {
                ShowSevereItemNotFound(state, eoh, cAlphaFieldNames(13), Alphas(13));
                ErrorsFound = true;
            }

            //   calculate sensible case load at design conditions
            // Case sensible capacity used for error messages
            Real64 DesignSensibleCap = RefrigCase(CaseNum).RateTotCapPerLength * (1.0 - RefrigCase(CaseNum).RatedLHR) * RefrigCase(CaseNum).RatedRTF *
                                       RefrigCase(CaseNum).Length;

            //   calculate case heat gain = lights + fans + anti-sweat
            Real64 CaseHeatGain =
                ((RefrigCase(CaseNum).RatedLightingPower * RefrigCase(CaseNum).LightingFractionToCase) +
                 (RefrigCase(CaseNum).AntiSweatPower * RefrigCase(CaseNum).ASHeaterFractionToCase) + RefrigCase(CaseNum).STDFanPower) *
                RefrigCase(CaseNum).Length;

            //   sensible case credits are calculated as the difference between the design sensible capacity and the case heat gain
            RefrigCase(CaseNum).DesignSensCaseCredit = DesignSensibleCap - CaseHeatGain;

            //   compare case loads to design capacity
            if (DesignSensibleCap < CaseHeatGain) {
                ShowSevereError(
                    state,
                    format("{}{}=\"{}\", the sum of lighting, fan, and anti-sweat heater energy is greater than refrigerated case sensible capacity",
                           RoutineName,
                           CurrentModuleObject,
                           RefrigCase(CaseNum).Name));
                ErrorsFound = true;
            }

            if (lAlphaBlanks(14)) {
            } else if ((RefrigCase(CaseNum).caseCreditFracSched = Sched::GetSchedule(state, Alphas(14))) == nullptr) {
                ShowSevereItemNotFound(state, eoh, cAlphaFieldNames(14), Alphas(14));
                ErrorsFound = true;
            } else if (!RefrigCase(CaseNum).caseCreditFracSched->checkMinMaxVals(state, Clusive::In, 0.0, Clusive::In, 1.0)) {
                Sched::ShowSevereBadMinMax(state, eoh, cAlphaFieldNames(14), Alphas(14), Clusive::In, 0.0, Clusive::In, 1.0);
                ErrorsFound = true;
            }

            RefrigCase(CaseNum).DesignRatedCap = RefrigCase(CaseNum).RateTotCapPerLength * RefrigCase(CaseNum).Length;
            RefrigCase(CaseNum).DesignLatentCap = RefrigCase(CaseNum).DesignRatedCap * RefrigCase(CaseNum).RatedLHR * RefrigCase(CaseNum).RatedRTF;
            RefrigCase(CaseNum).DesignDefrostCap = RefrigCase(CaseNum).DefrostPower * RefrigCase(CaseNum).Length;
            RefrigCase(CaseNum).DesignLighting = RefrigCase(CaseNum).LightingPower * RefrigCase(CaseNum).Length;
            RefrigCase(CaseNum).DesignFanPower = RefrigCase(CaseNum).OperatingFanPower * RefrigCase(CaseNum).Length;

            // Design evaporating temperature:  for a DX system, saturated temperature for pressure leaving case
            //                              :  for a liquid system, liquid temperature entering case
            NumNum = 20;
            if (!lNumericBlanks(NumNum)) {
                RefrigCase(CaseNum).EvapTempDesign = Numbers(NumNum);
                if (RefrigCase(CaseNum).EvapTempDesign >= RefrigCase(CaseNum).Temperature) {
                    ShowSevereError(state,
                                    format("{}{}=\"{}\" {} must be below {}",
                                           RoutineName,
                                           CurrentModuleObject,
                                           RefrigCase(CaseNum).Name,
                                           cNumericFieldNames(NumNum),
                                           cNumericFieldNames(7)));
                    ErrorsFound = true;
                }
            } else {
                RefrigCase(CaseNum).EvapTempDesign = RefrigCase(CaseNum).Temperature - DelEvapTDefault;
                //    default 5C less than case operating temperature
            }

            NumNum = 21;
            if (!lNumericBlanks(NumNum)) {
                RefrigCase(CaseNum).RefrigInventory = Numbers(NumNum);
                RefrigCase(CaseNum).DesignRefrigInventory = RefrigCase(CaseNum).RefrigInventory * RefrigCase(CaseNum).Length;
                if (RefrigCase(CaseNum).RefrigInventory < 0.0) {
                    ShowSevereError(state,
                                    format("{}{}=\"{}\" {} must be a positive number.",
                                           RoutineName,
                                           CurrentModuleObject,
                                           RefrigCase(CaseNum).Name,
                                           cNumericFieldNames(NumNum)));
                    ErrorsFound = true;
                }
            } else {
                RefrigCase(CaseNum).RefrigInventory = 0.0;
            }

        } // Individual refrigerated cases
    } //(NumSimulationCases > 0 )

    //************ START WALK IN COOLER INPUT **************

    if (state.dataRefrigCase->NumSimulationWalkIns > 0) {
        CurrentModuleObject = "Refrigeration:WalkIn";
        for (int WalkInID = 1; WalkInID <= state.dataRefrigCase->NumSimulationWalkIns; ++WalkInID) {
            state.dataInputProcessing->inputProcessor->getObjectItem(state,
                                                                     CurrentModuleObject,
                                                                     WalkInID,
                                                                     Alphas,
                                                                     NumAlphas,
                                                                     Numbers,
                                                                     NumNumbers,
                                                                     IOStatus,
                                                                     lNumericBlanks,
                                                                     lAlphaBlanks,
                                                                     cAlphaFieldNames,
                                                                     cNumericFieldNames);

            ErrorObjectHeader eoh{routineName, CurrentModuleObject, Alphas(1)};

            WalkIn(WalkInID).Name = Alphas(1);

            if (lAlphaBlanks(2)) {
                WalkIn(WalkInID).availSched = Sched::GetScheduleAlwaysOn(state);
            } else if ((WalkIn(WalkInID).availSched = Sched::GetSchedule(state, Alphas(2))) == nullptr) {
                ShowSevereItemNotFound(state, eoh, cAlphaFieldNames(2), Alphas(2));
                ErrorsFound = true;
            } else if (!WalkIn(WalkInID).availSched->checkMinMaxVals(state, Clusive::In, 0.0, Clusive::In, 1.0)) {
                Sched::ShowSevereBadMinMax(state, eoh, cAlphaFieldNames(2), Alphas(2), Clusive::In, 0.0, Clusive::In, 1.0);
                ErrorsFound = true;
            }

            WalkIn(WalkInID).DesignRatedCap = Numbers(1);
            if (Numbers(1) <= 0.0) {
                ShowSevereError(
                    state,
                    format(
                        "{}{}=\"{}\", {} must be greater than 0 W", RoutineName, CurrentModuleObject, WalkIn(WalkInID).Name, cNumericFieldNames(1)));
                ErrorsFound = true;
            }

            if (!lNumericBlanks(2)) {
                WalkIn(WalkInID).Temperature = Numbers(2);
            } else {
                ShowSevereEmptyField(state, eoh, cNumericFieldNames(2));
                ErrorsFound = true;
            }

            if (!lNumericBlanks(3)) {
                WalkIn(WalkInID).TEvapDesign = Numbers(3);
            } else {
                ShowSevereEmptyField(state, eoh, cNumericFieldNames(3));
                ErrorsFound = true;
            }

            if (!lNumericBlanks(4)) {
                WalkIn(WalkInID).HeaterPower = Numbers(4);
            } else {
                ShowSevereEmptyField(state, eoh, cNumericFieldNames(4));
                ErrorsFound = true;
            }

            AlphaNum = 3;
            if (lAlphaBlanks(AlphaNum)) {
                WalkIn(WalkInID).heaterSched = Sched::GetScheduleAlwaysOn(state); // Not an availability schedule, but defaults to constant-1.0
            } else if ((WalkIn(WalkInID).heaterSched = Sched::GetSchedule(state, Alphas(AlphaNum))) == nullptr) {
                ShowSevereItemNotFound(state, eoh, cAlphaFieldNames(AlphaNum), Alphas(AlphaNum));
                ErrorsFound = true;
            } else if (!WalkIn(WalkInID).heaterSched->checkMinMaxVals(state, Clusive::In, 0.0, Clusive::In, 1.0)) {
                Sched::ShowSevereBadMinMax(state, eoh, cAlphaFieldNames(AlphaNum), Alphas(AlphaNum), Clusive::In, 0.0, Clusive::In, 1.0);
                ErrorsFound = true;
            }

            if (!lNumericBlanks(5) && Numbers(5) > 0.0) {
                WalkIn(WalkInID).CoilFanPower = Numbers(5);
            } else {
                ShowWarningError(state,
                                 format("{}{}=\"{}\", {} was not input or was less than 0 and default of 375.0 W will be used ",
                                        RoutineName,
                                        CurrentModuleObject,
                                        WalkIn(WalkInID).Name,
                                        cNumericFieldNames(5)));
                WalkIn(WalkInID).CoilFanPower = 375.0; // default value = 1/2 hp
            }

            if (lNumericBlanks(6)) {
                WalkIn(WalkInID).CircFanPower = 0.0;
            } else {
                WalkIn(WalkInID).CircFanPower = Numbers(6);
                if (Numbers(7) < 0.0) {
                    ShowSevereError(state,
                                    format("{}{}=\"{}\", {} must be greater than >= 0 W",
                                           RoutineName,
                                           CurrentModuleObject,
                                           WalkIn(WalkInID).Name,
                                           cNumericFieldNames(6)));
                    ErrorsFound = true;
                }
            }

            if (!lNumericBlanks(7)) {
                WalkIn(WalkInID).DesignLighting = Numbers(7);
            } else {
                ShowSevereEmptyField(state, eoh, cNumericFieldNames(7));
                ErrorsFound = true;
            }

            AlphaNum = 4;
            if (lAlphaBlanks(AlphaNum)) {
                WalkIn(WalkInID).lightingSched = Sched::GetScheduleAlwaysOn(state); // Not an availability schedule, but defaults to constant-1.0
            } else if ((WalkIn(WalkInID).lightingSched = Sched::GetSchedule(state, Alphas(AlphaNum))) == nullptr) {
                ShowSevereItemNotFound(state, eoh, cAlphaFieldNames(AlphaNum), Alphas(AlphaNum));
                ErrorsFound = true;
            } else if (!WalkIn(WalkInID).lightingSched->checkMinMaxVals(state, Clusive::In, 0.0, Clusive::In, 1.0)) {
                Sched::ShowSevereBadMinMax(state, eoh, cAlphaFieldNames(AlphaNum), Alphas(AlphaNum), Clusive::In, 0.0, Clusive::In, 1.0);
                ErrorsFound = true;
            }

            // Input walk-in cooler defrost information
            AlphaNum = 5;
            if (lAlphaBlanks(AlphaNum)) {
                WalkIn(WalkInID).defrostType = DefrostType::Elec;
            } else if ((WalkIn(WalkInID).defrostType = static_cast<DefrostType>(getEnumValue(defrostTypeNamesUC, Alphas(AlphaNum)))) ==
                       DefrostType::Invalid) {
                ShowSevereInvalidKey(state, eoh, cAlphaFieldNames(AlphaNum), Alphas(AlphaNum));
                ErrorsFound = true;
            }

            AlphaNum = 6;
            if (lAlphaBlanks(AlphaNum)) {
                WalkIn(WalkInID).DefrostControlType = DefrostCtrlType::Sched;
            } else if ((WalkIn(WalkInID).DefrostControlType = static_cast<DefrostCtrlType>(getEnumValue(defrostCtrlTypeNamesUC, Alphas(AlphaNum)))) ==
                       DefrostCtrlType::Invalid) {
                ShowSevereInvalidKey(state, eoh, cAlphaFieldNames(AlphaNum), Alphas(AlphaNum));
                ErrorsFound = true;
            } // defrost control type

            // convert defrost schedule name to pointer
            AlphaNum = 7;

            if (lAlphaBlanks(AlphaNum)) {
                ShowSevereEmptyField(state, eoh, cAlphaFieldNames(AlphaNum));
                ErrorsFound = true;
            } else if ((WalkIn(WalkInID).defrostSched = Sched::GetSchedule(state, Alphas(AlphaNum))) == nullptr) {
                ShowSevereItemNotFound(state, eoh, cAlphaFieldNames(AlphaNum), Alphas(AlphaNum));
                ErrorsFound = true;
            } else if (!WalkIn(WalkInID).defrostSched->checkMinMaxVals(state, Clusive::In, 0.0, Clusive::In, 1.0)) {
                Sched::ShowSevereBadMinMax(state, eoh, cAlphaFieldNames(AlphaNum), Alphas(AlphaNum), Clusive::In, 0.0, Clusive::In, 1.0);
                ErrorsFound = true;
            }

            // convert defrost drip-down schedule name to pointer
            // some defrost types do not use drip-down schedules, use same defrost schedule pointer in that case
            AlphaNum = 8;
            if (lAlphaBlanks(AlphaNum)) { // blank input so use drip down schedule for defrost
                WalkIn(WalkInID).defrostDripDownSched = WalkIn(WalkInID).defrostSched;
            } else if ((WalkIn(WalkInID).defrostDripDownSched = Sched::GetSchedule(state, Alphas(AlphaNum))) == nullptr) {
                ShowSevereItemNotFound(state, eoh, cAlphaFieldNames(AlphaNum), Alphas(AlphaNum));
                ErrorsFound = true;
            } else if (!WalkIn(WalkInID).defrostDripDownSched->checkMinMaxVals(state, Clusive::In, 0.0, Clusive::In, 1.0)) {
                Sched::ShowSevereBadMinMax(state, eoh, cAlphaFieldNames(AlphaNum), Alphas(AlphaNum), Clusive::In, 0.0, Clusive::In, 1.0);
                ErrorsFound = true;
            }

            if (WalkIn(WalkInID).defrostType == DefrostType::OffCycle || WalkIn(WalkInID).defrostType == DefrostType::None) {
                WalkIn(WalkInID).DefrostCapacity = 0.0;
                // Don't even need to read N8 or N9 for those two defrost types.
            } else { // have electric or hot gas/brine defrost
                if ((lNumericBlanks(8)) || (Numbers(8) <= 0.0)) {
                    ShowSevereError(state,
                                    format("{}{}=\"{}\", {} must be input and greater than or equal to 0 W for {} {}",
                                           RoutineName,
                                           CurrentModuleObject,
                                           WalkIn(WalkInID).Name,
                                           cNumericFieldNames(8),
                                           cAlphaFieldNames(5),
                                           Alphas(5)));
                    ErrorsFound = true;
                } else {
                    WalkIn(WalkInID).DefrostCapacity = Numbers(8);
                } // Blank  or negative N8

                // defaults for defrost energy fraction are 0.7 for elec defrost and 0.3 for warm fluid
                // note this value is only used for temperature terminated defrost control type
                if (WalkIn(WalkInID).defrostType == DefrostType::Elec) {
                    WalkIn(WalkInID).DefEnergyFraction = 0.7;
                }
                if (WalkIn(WalkInID).defrostType == DefrostType::Fluid) {
                    WalkIn(WalkInID).DefEnergyFraction = 0.3;
                }
                if (!lNumericBlanks(9)) {
                    if ((Numbers(9) > 1.0) || (Numbers(9) < 0.0)) {
                        ShowWarningError(state,
                                         format("{}{}=\"{}\", {} must be between 0 and 1, default values will be used.",
                                                RoutineName,
                                                CurrentModuleObject,
                                                WalkIn(WalkInID).Name,
                                                cNumericFieldNames(9)));
                    } else {
                        WalkIn(WalkInID).DefEnergyFraction = Numbers(9);
                    } // number out of range
                } // lnumericblanks
            } // defrost type

            // convert restocking schedule name to pointer, default of 0.1 is assigned inside walkin subroutine if blank
            AlphaNum = 9;
            if (lAlphaBlanks(AlphaNum)) {
            } else if ((WalkIn(WalkInID).stockingSched = Sched::GetSchedule(state, Alphas(AlphaNum))) == nullptr) {
                ShowSevereItemNotFound(state, eoh, cAlphaFieldNames(AlphaNum), Alphas(AlphaNum));
                ErrorsFound = true;
            }

            WalkIn(WalkInID).DesignRefrigInventory = 0.0;
            if (!lNumericBlanks(10)) {
                WalkIn(WalkInID).DesignRefrigInventory = Numbers(10);
            }

            if (!lNumericBlanks(11)) {
                WalkIn(WalkInID).FloorArea = Numbers(11);
            } else {
                ShowSevereError(
                    state, format("{}{}=\"{}\", {} must be input", RoutineName, CurrentModuleObject, WalkIn(WalkInID).Name, cNumericFieldNames(11)));
                ErrorsFound = true;
            }

            if (lNumericBlanks(12)) {
                WalkIn(WalkInID).FloorUValue = DefaultWISurfaceUValue;
            } else {
                WalkIn(WalkInID).FloorUValue = Numbers(12);
                if (Numbers(12) <= 0.0) {
                    ShowSevereError(
                        state,
                        format("{}{}=\"{}\", {} must be > 0.", RoutineName, CurrentModuleObject, WalkIn(WalkInID).Name, cNumericFieldNames(12)));
                    ErrorsFound = true;
                }
            }

            // Calculate the number of zones exposed to walk-in based on number of input fields, all integer math,
            // This approach used because last zone could have less than NumWIFieldsPerZone due to optional values
            int NumWIFieldsPerZone = NumWIAlphaFieldsPerZone + NumWINumberFieldsPerZone;
            int NumWIFieldsTotal = NumNumbers + NumAlphas - NumWIAlphaFieldsBeforeZoneInput - NumWINumberFieldsBeforeZoneInput;
            int NumZones = 1;
            if (NumWIFieldsTotal > NumWIFieldsPerZone) {
                NumZones = 2;
            }
            if (NumWIFieldsTotal > (2 * NumWIFieldsPerZone)) {
                NumZones = 3;
            }
            if (NumWIFieldsTotal > (3 * NumWIFieldsPerZone)) {
                NumZones = 4;
            }
            if (NumWIFieldsTotal > (4 * NumWIFieldsPerZone)) {
                NumZones = 5;
            }
            if (NumWIFieldsTotal > (5 * NumWIFieldsPerZone)) {
                NumZones = 6;
            }
            WalkIn(WalkInID).NumZones = NumZones;

            // All variables for walk-in/zone interactions need to be allocated after know number of zones
            // Autodesk Missing initialization added below: At least SensZoneCreditRate was used uninitialized
            if (!allocated(WalkIn(WalkInID).ZoneName)) {
                WalkIn(WalkInID).ZoneName.allocate(NumZones);
            }
            if (!allocated(WalkIn(WalkInID).ZoneNum)) {
                WalkIn(WalkInID).ZoneNum.allocate(NumZones) = 0;
            }
            if (!allocated(WalkIn(WalkInID).ZoneNodeNum)) {
                WalkIn(WalkInID).ZoneNodeNum.allocate(NumZones) = 0;
            }
            if (!allocated(WalkIn(WalkInID).SurfaceArea)) {
                WalkIn(WalkInID).SurfaceArea.allocate(NumZones) = 0.0;
            }
            if (!allocated(WalkIn(WalkInID).UValue)) {
                WalkIn(WalkInID).UValue.allocate(NumZones) = 0.0;
            }
            if (!allocated(WalkIn(WalkInID).UValueGlassDr)) {
                WalkIn(WalkInID).UValueGlassDr.allocate(NumZones) = 0.0;
            }
            if (!allocated(WalkIn(WalkInID).glassDoorOpenScheds)) {
                WalkIn(WalkInID).glassDoorOpenScheds.allocate(NumZones) = nullptr; // What is this?
            }
            if (!allocated(WalkIn(WalkInID).AreaGlassDr)) {
                WalkIn(WalkInID).AreaGlassDr.allocate(NumZones) = 0.0;
            }
            if (!allocated(WalkIn(WalkInID).HeightGlassDr)) {
                WalkIn(WalkInID).HeightGlassDr.allocate(NumZones) = 0.0;
            }
            if (!allocated(WalkIn(WalkInID).UValueStockDr)) {
                WalkIn(WalkInID).UValueStockDr.allocate(NumZones) = 0.0;
            }
            if (!allocated(WalkIn(WalkInID).stockDoorOpenScheds)) {
                WalkIn(WalkInID).stockDoorOpenScheds.allocate(NumZones) = nullptr; // What is this?
            }
            if (!allocated(WalkIn(WalkInID).StockDoorProtectType)) {
                WalkIn(WalkInID).StockDoorProtectType.allocate(NumZones) = WIStockDoor::Invalid;
            }
            if (!allocated(WalkIn(WalkInID).AreaStockDr)) {
                WalkIn(WalkInID).AreaStockDr.allocate(NumZones) = 0.0;
            }
            if (!allocated(WalkIn(WalkInID).HeightStockDr)) {
                WalkIn(WalkInID).HeightStockDr.allocate(NumZones) = 0.0;
            }
            if (!allocated(WalkIn(WalkInID).SensZoneCreditRate)) {
                WalkIn(WalkInID).SensZoneCreditRate.allocate(NumZones) = 0.0;
            }
            if (!allocated(WalkIn(WalkInID).SensZoneCreditCoolRate)) {
                WalkIn(WalkInID).SensZoneCreditCoolRate.allocate(NumZones) = 0.0;
            }
            if (!allocated(WalkIn(WalkInID).SensZoneCreditCool)) {
                WalkIn(WalkInID).SensZoneCreditCool.allocate(NumZones) = 0.0;
            }
            if (!allocated(WalkIn(WalkInID).SensZoneCreditHeatRate)) {
                WalkIn(WalkInID).SensZoneCreditHeatRate.allocate(NumZones) = 0.0;
            }
            if (!allocated(WalkIn(WalkInID).SensZoneCreditHeat)) {
                WalkIn(WalkInID).SensZoneCreditHeat.allocate(NumZones) = 0.0;
            }
            if (!allocated(WalkIn(WalkInID).LatZoneCreditRate)) {
                WalkIn(WalkInID).LatZoneCreditRate.allocate(NumZones) = 0.0;
            }
            if (!allocated(WalkIn(WalkInID).LatZoneCredit)) {
                WalkIn(WalkInID).LatZoneCredit.allocate(NumZones) = 0.0;
            }

            int AStart = NumWIAlphaFieldsBeforeZoneInput + 1;
            int NStart = NumWINumberFieldsBeforeZoneInput + 1;
            for (int ZoneID = 1; ZoneID <= NumZones; ++ZoneID) {
                // Get the Zone node number from the zone name
                // The Zone Node is needed to get the zone's ambient conditions, DataGlobals::NumOfZones from dataglobals
                WalkIn(WalkInID).ZoneName(ZoneID) = Alphas(AStart);
                WalkIn(WalkInID).ZoneNum(ZoneID) = Util::FindItemInList(Alphas(AStart), state.dataHeatBal->Zone);

                if (WalkIn(WalkInID).ZoneNum(ZoneID) == 0) {
                    ShowSevereItemNotFound(state, eoh, cAlphaFieldNames(AStart), Alphas(AStart));
                    ErrorsFound = true;
                } else {
                    state.dataRefrigCase->RefrigPresentInZone(WalkIn(WalkInID).ZoneNum(ZoneID)) = true;
                }
                WalkIn(WalkInID).ZoneNodeNum(ZoneID) = DataZoneEquipment::GetSystemNodeNumberForZone(state, WalkIn(WalkInID).ZoneNum(ZoneID));
                if (WalkIn(WalkInID).ZoneNum(ZoneID) >= 0) {
                    if (WalkIn(WalkInID).ZoneNodeNum(ZoneID) == 0) {
                        ShowSevereItemNotFound(state, eoh, cAlphaFieldNames(AStart), Alphas(AStart));
                        ShowContinueError(state, ".. Walk Ins must reference a controlled Zone (appear in a ZoneHVAC:EquipmentConnections object.");
                        ErrorsFound = true;
                    }
                }

                if (!lNumericBlanks(NStart)) {
                    WalkIn(WalkInID).SurfaceArea(ZoneID) = Numbers(NStart);
                } else {
                    ShowSevereError(state,
                                    format("{}{}=\"{}\", {} must be input for Zone: {}",
                                           RoutineName,
                                           CurrentModuleObject,
                                           WalkIn(WalkInID).Name,
                                           cNumericFieldNames(NStart),
                                           WalkIn(WalkInID).ZoneName(ZoneID)));
                    ErrorsFound = true;
                }

                if (lNumericBlanks(NStart + 1)) {
                    WalkIn(WalkInID).UValue(ZoneID) = DefaultWISurfaceUValue;
                } else {
                    WalkIn(WalkInID).UValue(ZoneID) = Numbers(NStart + 1);
                    if (Numbers(NStart + 1) <= 0.0) {
                        ShowSevereError(state,
                                        format(R"({}{}="{}", Zone="{}", {} must be > 0.)",
                                               RoutineName,
                                               CurrentModuleObject,
                                               WalkIn(WalkInID).Name,
                                               WalkIn(WalkInID).ZoneName(ZoneID),
                                               cNumericFieldNames(NStart + 1)));
                        ErrorsFound = true;
                    }
                }

                // start IF set for glass doors in this zone
                WalkIn(WalkInID).AreaGlassDr(ZoneID) = 0.0;
                WalkIn(WalkInID).HeightGlassDr(ZoneID) = 0.0;
                WalkIn(WalkInID).UValueGlassDr(ZoneID) = 0.0;
                if (!lNumericBlanks(NStart + 2)) {
                    WalkIn(WalkInID).AreaGlassDr(ZoneID) = Numbers(NStart + 2);

                    WalkIn(WalkInID).HeightGlassDr(ZoneID) = DefaultWIHeightGlassDr;
                    if (!lNumericBlanks(NStart + 3)) {
                        WalkIn(WalkInID).HeightGlassDr(ZoneID) = Numbers(NStart + 3);
                    }

                    WalkIn(WalkInID).UValueGlassDr(ZoneID) = DefaultWIUValueGlassDr;
                    if (!lNumericBlanks(NStart + 4)) {
                        WalkIn(WalkInID).UValueGlassDr(ZoneID) = Numbers(NStart + 4);
                    }

                    // convert door opening schedule name to pointer, default of 0.1 is assigned inside walkin subroutine if blank
                    if (lAlphaBlanks(AStart + 1)) {
                    } else if ((WalkIn(WalkInID).glassDoorOpenScheds(ZoneID) = Sched::GetSchedule(state, Alphas(AStart + 1))) == nullptr) {
                        ShowSevereItemNotFound(state, eoh, cAlphaFieldNames(AStart + 1), Alphas(AStart + 1));
                        ErrorsFound = true;
                    } else if (!WalkIn(WalkInID).glassDoorOpenScheds(ZoneID)->checkMinMaxVals(state, Clusive::In, 0.0, Clusive::In, 1.0)) {
                        Sched::ShowSevereBadMinMax(state, eoh, cAlphaFieldNames(AStart + 1), Alphas(AStart + 1), Clusive::In, 0.0, Clusive::In, 1.0);
                        ErrorsFound = true;
                    } // blank on door opening schedule (AStart + 1)
                } // have glassdoor area facing zone (blank on lNumericBlanks(NStart+2))

                // start IF set for stock doors in this zone
                WalkIn(WalkInID).AreaStockDr(ZoneID) = 0.0;
                WalkIn(WalkInID).HeightStockDr(ZoneID) = 0.0;
                WalkIn(WalkInID).UValueStockDr(ZoneID) = 0.0;
                if (!lNumericBlanks(NStart + 5)) {
                    WalkIn(WalkInID).AreaStockDr(ZoneID) = Numbers(NStart + 5);

                    WalkIn(WalkInID).HeightStockDr(ZoneID) = DefaultWIHeightStockDr;
                    if (!lNumericBlanks(NStart + 6)) {
                        WalkIn(WalkInID).HeightStockDr(ZoneID) = Numbers(NStart + 6);
                    }

                    WalkIn(WalkInID).UValueStockDr(ZoneID) = DefaultWIUValueStockDr;
                    if (!lNumericBlanks(NStart + 7)) {
                        WalkIn(WalkInID).UValueStockDr(ZoneID) = Numbers(NStart + 7);
                    }

                    // convert door opening schedule name to pointer, default of 0.1 is assigned inside walkin subroutine if blank
                    if (lAlphaBlanks(AStart + 2)) {
                    } else if ((WalkIn(WalkInID).stockDoorOpenScheds(ZoneID) = Sched::GetSchedule(state, Alphas(AStart + 2))) == nullptr) {
                        ShowSevereItemNotFound(state, eoh, cAlphaFieldNames(AStart + 2), Alphas(AStart + 2));
                        ErrorsFound = true;
                    } else if (!WalkIn(WalkInID).stockDoorOpenScheds(ZoneID)->checkMinMaxVals(state, Clusive::In, 0.0, Clusive::In, 1.0)) {
                        Sched::ShowSevereBadMinMax(state, eoh, cAlphaFieldNames(AStart + 2), Alphas(AStart + 2), Clusive::In, 0.0, Clusive::In, 1.0);
                        ErrorsFound = true;
                    } // blank on door opening schedule (AStart + 2)

                    if (lAlphaBlanks(AStart + 3)) {
                        // default air curtain
                        WalkIn(WalkInID).StockDoorProtectType(ZoneID) = WIStockDoor::AirCurtain;
                    } else if ((WalkIn(WalkInID).StockDoorProtectType(ZoneID) =
                                    static_cast<WIStockDoor>(getEnumValue(wiStockDoorNamesUC, Alphas(AStart + 3)))) == WIStockDoor::Invalid) {
                        ShowSevereInvalidKey(state, eoh, cAlphaFieldNames(AStart + 3), Alphas(AStart + 3));
                        ErrorsFound = true;
                    } // stock door protection (AStart + 3) blank
                } // have Stockdoor area facing zone

                AStart += NumWIAlphaFieldsPerZone;
                NStart += NumWINumberFieldsPerZone;
            } // Zones for Walk Ins
        } // Individual Walk Ins
    } //(NumSimulationWalkIns > 0 )

    //************* Start Indiv Refrig Air Chillers

    if (state.dataRefrigCase->NumSimulationRefrigAirChillers > 0) {
        CurrentModuleObject = "Refrigeration:AirChiller";
        for (int CoilID = 1; CoilID <= state.dataRefrigCase->NumSimulationRefrigAirChillers; ++CoilID) {
            // A1
            AlphaNum = 1;
            state.dataInputProcessing->inputProcessor->getObjectItem(state,
                                                                     CurrentModuleObject,
                                                                     CoilID,
                                                                     Alphas,
                                                                     NumAlphas,
                                                                     Numbers,
                                                                     NumNumbers,
                                                                     IOStatus,
                                                                     lNumericBlanks,
                                                                     lAlphaBlanks,
                                                                     cAlphaFieldNames,
                                                                     cNumericFieldNames);

            ErrorObjectHeader eoh{routineName, CurrentModuleObject, Alphas(1)};

            Util::IsNameEmpty(state, Alphas(1), CurrentModuleObject, ErrorsFound);

            WarehouseCoil(CoilID).Name = Alphas(AlphaNum);

            // A2
            ++AlphaNum;
            if (lAlphaBlanks(AlphaNum)) {
                WarehouseCoil(CoilID).availSched = Sched::GetScheduleAlwaysOn(state);
            } else if ((WarehouseCoil(CoilID).availSched = Sched::GetSchedule(state, Alphas(AlphaNum))) == nullptr) {
                ShowSevereItemNotFound(state, eoh, cAlphaFieldNames(AlphaNum), Alphas(AlphaNum));
                ErrorsFound = true;
            } else if (!WarehouseCoil(CoilID).availSched->checkMinMaxVals(state, Clusive::In, 0.0, Clusive::In, 1.0)) {
                Sched::ShowSevereBadMinMax(state, eoh, cAlphaFieldNames(AlphaNum), Alphas(AlphaNum), Clusive::In, 0.0, Clusive::In, 1.0);
                ErrorsFound = true;
            }

            // Input capacity rating type
            // bbbbb input values (DT1 or DTM type)translate DT1 to DTm here because node will give avg temp?
            //      ask whether ceiling or floor mounted? - effects translation from DT1 to DTM
            //      input coil condition, wet or dry OR input rating basis, European SC1, SC2 etc., have to combine with refrigerant factor)
            //      rated capacity, BAC give W/C, European gives W
            //      fin material factor, default 1
            //      refrigerant factor (factor of both refrigerant and Tevap)

            // A3
            ++AlphaNum;
            if (lAlphaBlanks(AlphaNum)) {
                ShowSevereEmptyField(state, eoh, cAlphaFieldNames(AlphaNum));
                ErrorsFound = true;
            } else if ((WarehouseCoil(CoilID).ratingType = static_cast<RatingType>(getEnumValue(ratingTypeNamesUC, Alphas(AlphaNum)))) ==
                       RatingType::Invalid) {

                ShowSevereInvalidKey(state, eoh, cAlphaFieldNames(AlphaNum), Alphas(AlphaNum));
                ErrorsFound = true;
            }

            // Here have to do select case with one numeric field with units of W and the second with units of W/deltaC,
            //  (RatedRH field only used for RatedCapacityTotal type)
            { // Why is this a new scope
                switch (WarehouseCoil(CoilID).ratingType) {
                case RatingType::UnitLoadFactorSens: {
                    // N1
                    NumNum = 1;
                    if (!lNumericBlanks(NumNum) && Numbers(NumNum) > 0.0) {
                        WarehouseCoil(CoilID).UnitLoadFactorSens = Numbers(NumNum);
                    } else {
                        ShowSevereError(state,
                                        format("{}{}=\"{}\", {} must be input and be greater than 0 W/C",
                                               RoutineName,
                                               CurrentModuleObject,
                                               WarehouseCoil(CoilID).Name,
                                               cNumericFieldNames(NumNum)));
                        ErrorsFound = true;
                    }
                } break;

                case RatingType::RatedCapacityTotal: {
                    // N2
                    NumNum = 2; // advance past rating in W/C to N2 with rating in W
                    if (!lNumericBlanks(NumNum) && Numbers(NumNum) > 0.0) {
                        WarehouseCoil(CoilID).RatedCapTotal = Numbers(NumNum);
                        // N3
                        NumNum = 3; // read rated RH only for this type of rating at N3
                        if (lNumericBlanks(NumNum)) {
                            WarehouseCoil(CoilID).RatedRH = 0.85;
                        } else {
                            if (Numbers(NumNum) <= 0.0 || Numbers(NumNum) >= 100.0) {
                                ShowSevereError(state,
                                                format("{}{}=\"{}\", {} must be greater than 0% and less than 100%",
                                                       RoutineName,
                                                       CurrentModuleObject,
                                                       WarehouseCoil(CoilID).Name,
                                                       cNumericFieldNames(NumNum)));
                                ErrorsFound = true;
                            }
                            WarehouseCoil(CoilID).RatedRH = Numbers(NumNum) / 100.0;
                        }
                    } else {
                        ShowSevereError(state,
                                        format("{}{}=\"{}\", {} must be input and be greater than 0 W",
                                               RoutineName,
                                               CurrentModuleObject,
                                               WarehouseCoil(CoilID).Name,
                                               cNumericFieldNames(NumNum)));
                        ErrorsFound = true;
                    }
                } break;

                case RatingType::EuropeanSC1Std: {
                    // N2
                    NumNum = 2; // advance past rating in W/C to rating in W at N2
                    if (!lNumericBlanks(NumNum) && Numbers(NumNum) > 0.0) {
                        WarehouseCoil(CoilID).RatedSensibleCap = Numbers(NumNum);
                        WarehouseCoil(CoilID).SCIndex = 1;
                    } else {
                        ShowSevereError(state,
                                        format("{}{}=\"{}\", {} must be input and be greater than 0 W",
                                               RoutineName,
                                               CurrentModuleObject,
                                               WarehouseCoil(CoilID).Name,
                                               cNumericFieldNames(NumNum)));
                        ErrorsFound = true;
                    }
                } break;

                case RatingType::EuropeanSC1Nom: {
                    // N2
                    NumNum = 2; // advance past rating in W/C to rating in W at N2
                    if (!lNumericBlanks(NumNum) && Numbers(NumNum) > 0.0) {
                        WarehouseCoil(CoilID).RatedCapTotal = Numbers(NumNum);
                        WarehouseCoil(CoilID).RatedSensibleCap = Numbers(NumNum) / EuropeanWetCoilFactor[0];
                        WarehouseCoil(CoilID).SCIndex = 1;
                    } else {
                        ShowSevereError(state,
                                        format("{}{}=\"{}\", {} must be input and be greater than 0 W",
                                               RoutineName,
                                               CurrentModuleObject,
                                               WarehouseCoil(CoilID).Name,
                                               cNumericFieldNames(NumNum)));
                        ErrorsFound = true;
                    }
                } break;

                case RatingType::EuropeanSC2Std: {
                    // N2
                    NumNum = 2; // advance past rating in W/C to rating in W at N2
                    if (!lNumericBlanks(NumNum) && Numbers(NumNum) > 0.0) {
                        WarehouseCoil(CoilID).RatedSensibleCap = Numbers(NumNum);
                        WarehouseCoil(CoilID).SCIndex = 2;
                    } else {
                        ShowSevereError(state,
                                        format("{}{}=\"{}\", {} must be input and be greater than 0 W",
                                               RoutineName,
                                               CurrentModuleObject,
                                               WarehouseCoil(CoilID).Name,
                                               cNumericFieldNames(NumNum)));
                        ErrorsFound = true;
                    }
                } break;

                case RatingType::EuropeanSC2Nom: {
                    // N2
                    NumNum = 2; // advance past rating in W/C to rating in W at N2
                    if (!lNumericBlanks(NumNum) && Numbers(NumNum) > 0.0) {
                        WarehouseCoil(CoilID).RatedCapTotal = Numbers(NumNum);
                        WarehouseCoil(CoilID).RatedSensibleCap = Numbers(NumNum) / EuropeanWetCoilFactor[1];
                        WarehouseCoil(CoilID).SCIndex = 2;
                    } else {
                        ShowSevereError(state,
                                        format("{}{}=\"{}\", {} must be input and be greater than 0 W",
                                               RoutineName,
                                               CurrentModuleObject,
                                               WarehouseCoil(CoilID).Name,
                                               cNumericFieldNames(NumNum)));
                        ErrorsFound = true;
                    }
                } break;

                case RatingType::EuropeanSC3Std: {
                    // N2
                    NumNum = 2; // advance past rating in W/C to rating in W at N2
                    if (!lNumericBlanks(NumNum) && Numbers(NumNum) > 0.0) {
                        WarehouseCoil(CoilID).RatedSensibleCap = Numbers(NumNum);
                        WarehouseCoil(CoilID).SCIndex = 3;
                    } else {
                        ShowSevereError(state,
                                        format("{}{}=\"{}\", {} must be input and be greater than 0 W",
                                               RoutineName,
                                               CurrentModuleObject,
                                               WarehouseCoil(CoilID).Name,
                                               cNumericFieldNames(NumNum)));
                        ErrorsFound = true;
                    }
                } break;

                case RatingType::EuropeanSC3Nom: {
                    // N2
                    NumNum = 2; // advance past rating in W/C to rating in W at N2
                    if (!lNumericBlanks(NumNum) && Numbers(NumNum) > 0.0) {
                        WarehouseCoil(CoilID).RatedCapTotal = Numbers(NumNum);
                        WarehouseCoil(CoilID).RatedSensibleCap = Numbers(NumNum) / EuropeanWetCoilFactor[2];
                        WarehouseCoil(CoilID).SCIndex = 3;
                    } else {
                        ShowSevereError(state,
                                        format("{}{}=\"{}\", {} must be input and be greater than 0 W",
                                               RoutineName,
                                               CurrentModuleObject,
                                               WarehouseCoil(CoilID).Name,
                                               cNumericFieldNames(NumNum)));
                        ErrorsFound = true;
                    }
                } break;

                case RatingType::EuropeanSC4Std: {
                    // N2
                    NumNum = 2; // advance past rating in W/C to rating in W at N2
                    if (!lNumericBlanks(NumNum) && Numbers(NumNum) > 0.0) {
                        WarehouseCoil(CoilID).RatedSensibleCap = Numbers(NumNum);
                        WarehouseCoil(CoilID).SCIndex = 4;
                    } else {
                        ShowSevereError(state,
                                        format("{}{}=\"{}\", {} must be input and be greater than 0 W",
                                               RoutineName,
                                               CurrentModuleObject,
                                               WarehouseCoil(CoilID).Name,
                                               cNumericFieldNames(NumNum)));
                        ErrorsFound = true;
                    }
                } break;

                case RatingType::EuropeanSC4Nom: {
                    // N2
                    NumNum = 2; // advance past rating in W/C to rating in W at N2
                    if (!lNumericBlanks(NumNum) && Numbers(NumNum) > 0.0) {
                        WarehouseCoil(CoilID).RatedCapTotal = Numbers(NumNum);
                        WarehouseCoil(CoilID).RatedSensibleCap = Numbers(NumNum) / EuropeanWetCoilFactor[3];
                        WarehouseCoil(CoilID).SCIndex = 4;
                    } else {
                        ShowSevereError(state,
                                        format("{}{}=\"{}\", {} must be input and be greater than 0 W",
                                               RoutineName,
                                               CurrentModuleObject,
                                               WarehouseCoil(CoilID).Name,
                                               cNumericFieldNames(NumNum)));
                        ErrorsFound = true;
                    }
                } break;

                case RatingType::EuropeanSC5Std: {
                    // N2
                    NumNum = 2; // advance past rating in W/C to rating in W at N2
                    if (!lNumericBlanks(NumNum) && Numbers(NumNum) > 0.0) {
                        WarehouseCoil(CoilID).RatedSensibleCap = Numbers(NumNum);
                        WarehouseCoil(CoilID).SCIndex = 5;
                    } else {
                        ShowSevereError(state,
                                        format("{}{}=\"{}\", {} must be input and be greater than 0 W",
                                               RoutineName,
                                               CurrentModuleObject,
                                               WarehouseCoil(CoilID).Name,
                                               cNumericFieldNames(NumNum)));
                        ErrorsFound = true;
                    }
                } break;

                case RatingType::EuropeanSC5Nom: {
                    // N2
                    NumNum = 2; // advance past rating in W/C to rating in W at N2
                    if (!lNumericBlanks(NumNum) && Numbers(NumNum) > 0.0) {
                        WarehouseCoil(CoilID).RatedCapTotal = Numbers(NumNum);
                        WarehouseCoil(CoilID).RatedSensibleCap = Numbers(NumNum) / EuropeanWetCoilFactor[4];
                        WarehouseCoil(CoilID).SCIndex = 5;
                    } else {
                        ShowSevereError(state,
                                        format("{}{}=\"{}\", {} must be input and be greater than 0 W",
                                               RoutineName,
                                               CurrentModuleObject,
                                               WarehouseCoil(CoilID).Name,
                                               cNumericFieldNames(NumNum)));
                        ErrorsFound = true;
                    }
                } break;

                default: {
                } break;
                }
            } // WarehouseCoil(CoilID)%RatingType

            // N4
            NumNum = 4;
            if (!lNumericBlanks(NumNum)) {
                WarehouseCoil(CoilID).TEvapDesign = Numbers(NumNum); // also used to rep inlet brine T later when add that option
            } else {
                ShowSevereError(
                    state,
                    format(
                        "{}{}=\"{}\", {} must be input", RoutineName, CurrentModuleObject, WarehouseCoil(CoilID).Name, cNumericFieldNames(NumNum)));
                ErrorsFound = true;
            }

            ++NumNum; // N5
            if (!lNumericBlanks(NumNum)) {
                WarehouseCoil(CoilID).RatedTemperatureDif = Numbers(NumNum);
                // INLET temperature - evaporating temperature, NOT room temp - evap temp
            } else {
                ShowSevereError(
                    state,
                    format(
                        "{}{}=\"{}\", {} must be input", RoutineName, CurrentModuleObject, WarehouseCoil(CoilID).Name, cNumericFieldNames(NumNum)));
                ErrorsFound = true;
            }

            ++NumNum; // N6
            if (!lNumericBlanks(NumNum)) {
                WarehouseCoil(CoilID).MaxTemperatureDif = Numbers(NumNum);
                // Maximum difference between INLET temperature - evaporating temperature, NOT room temp - evap temp
                // Important when cooling down space at start of environment or if large stocking loads imposed.
            } else {
                WarehouseCoil(CoilID).MaxTemperatureDif = 1.3 * WarehouseCoil(CoilID).RatedTemperatureDif;
                ShowWarningError(state,
                                 format("{}{}=\"{}\", {} not entered, default 1.3 times rated temperature difference will be used.",
                                        RoutineName,
                                        CurrentModuleObject,
                                        WarehouseCoil(CoilID).Name,
                                        cNumericFieldNames(NumNum)));
            }

            // Correction factor from manufacturer's rating for coil material, default 1.0
            ++NumNum;                                 // N7
            WarehouseCoil(CoilID).CorrMaterial = 1.0; // default value
            if (!lNumericBlanks(NumNum)) {
                WarehouseCoil(CoilID).CorrMaterial = Numbers(NumNum);
            }

            // Correction factor from manufacturer's rating for refrigerant, default 1.0
            ++NumNum;                                    // N8
            WarehouseCoil(CoilID).CorrRefrigerant = 1.0; // default value
            if (!lNumericBlanks(NumNum)) {
                WarehouseCoil(CoilID).CorrRefrigerant = Numbers(NumNum);
            }
            // ONLY used if the Capacity Rating Type is CapacityTotalSpecificConditions

            // Convert all European sensible capacities to sensible load factors
            if ((WarehouseCoil(CoilID).ratingType != RatingType::UnitLoadFactorSens) &&
                (WarehouseCoil(CoilID).ratingType != RatingType::RatedCapacityTotal)) {
                WarehouseCoil(CoilID).UnitLoadFactorSens = WarehouseCoil(CoilID).RatedSensibleCap / WarehouseCoil(CoilID).RatedTemperatureDif;
            }
            // Now have UnitLoadFactorSens for all except RatingType == RatedCapacityTotal

            // Apply material and refrigerant correction factors to sensible load factors
            if ((WarehouseCoil(CoilID).ratingType != RatingType::RatedCapacityTotal)) {
                WarehouseCoil(CoilID).UnitLoadFactorSens *= WarehouseCoil(CoilID).CorrMaterial * WarehouseCoil(CoilID).CorrRefrigerant;
            }
            // First calc of ratedsensiblecap for type type unitloadfactorsens
            WarehouseCoil(CoilID).RatedSensibleCap = WarehouseCoil(CoilID).UnitLoadFactorSens * WarehouseCoil(CoilID).RatedTemperatureDif;
            // A4    Enter capacity correction curve type
            AlphaNum = 4;
            if ((lAlphaBlanks(AlphaNum)) && (WarehouseCoil(CoilID).ratingType != RatingType::RatedCapacityTotal)) {
                // For all except RatedCapacityTotal - default to linear capacity factor approximating Nelson August 2010 ASHRAE journal
                WarehouseCoil(CoilID).SHRCorrType = SHRCorrectionType::SHR60;
            } else if (WarehouseCoil(CoilID).ratingType == RatingType::RatedCapacityTotal) {
                // For RatedCapacityTotal, the manufacturer's coil performance map is required
                // Specify the performance map with TabularRHxDT1xTRoom
                WarehouseCoil(CoilID).SHRCorrType = SHRCorrectionType::TabularRH_DT1_TRoom;
                if (!(Util::SameString(Alphas(AlphaNum), "TabularRHxDT1xTRoom"))) {
                    ShowWarningError(state,
                                     format(R"({}{}="{}", invalid {}="{}".)",
                                            RoutineName,
                                            CurrentModuleObject,
                                            WarehouseCoil(CoilID).Name,
                                            cAlphaFieldNames(AlphaNum),
                                            Alphas(AlphaNum)));
                    ShowContinueError(state,
                                      "The \"CapacityTotalSpecificConditions\" Capacity Rating Type has been specified for this air chiller.  "
                                      "This rating type requires ");
                    ShowContinueError(
                        state,
                        format(
                            R"(the "TabularRHxDT1xTRoom" correction curve.  Verify that a valid "TabularRHxDT1xTRoom" curve is specified in "{}".)",
                            cAlphaFieldNames(AlphaNum + 1)));
                }
            } else if ((WarehouseCoil(CoilID).SHRCorrType =
                            static_cast<SHRCorrectionType>(getEnumValue(shrCorrectionTypeNamesUC, Alphas(AlphaNum)))) == SHRCorrectionType::Invalid) {
                ShowSevereInvalidKey(state, eoh, cAlphaFieldNames(AlphaNum), Alphas(AlphaNum));
                ErrorsFound = true;
            }

            ++AlphaNum; // A5
            ++NumNum;   // N9
            switch (WarehouseCoil(CoilID).SHRCorrType) {
            case SHRCorrectionType::SHR60: {
                WarehouseCoil(CoilID).SHRCorrection60 = 1.48; // reference Nelson, ASHRAE journal August 2010 Fig 2
                if (!lNumericBlanks(NumNum)) {
                    WarehouseCoil(CoilID).SHRCorrection60 = Numbers(NumNum);
                }
                //(1.66667 would be a perfect effectiveness, 1.0 would be artificial coil that does only sensible)
                if (WarehouseCoil(CoilID).SHRCorrection60 > 1.67) {
                    WarehouseCoil(CoilID).SHRCorrection60 = 1.67;
                    ShowWarningError(state,
                                     format("{}{}=\"{}\", {} must be between 1 and 1.67, 1.67 will be used.",
                                            RoutineName,
                                            CurrentModuleObject,
                                            WarehouseCoil(CoilID).Name,
                                            cNumericFieldNames(NumNum)));
                }
                if (WarehouseCoil(CoilID).SHRCorrection60 < 1.0) {
                    WarehouseCoil(CoilID).SHRCorrection60 = 1.0;
                    ShowWarningError(state,
                                     format("{}{}=\"{}\", {} must be between 1 and 1.67, 1.00 will be used.",
                                            RoutineName,
                                            CurrentModuleObject,
                                            WarehouseCoil(CoilID).Name,
                                            cNumericFieldNames(NumNum)));
                }
            } break;
            case SHRCorrectionType::European: {
                // WarehouseCoil(CoilID)%SHRCorrectionCurvePtr = CurveManager::GetCurveIndex(state, 'ChillerEuropeanWetCoilFactor')
                // This is a place holder, currently use embedded constants for European ratings, future may want a curve
            } break;
            case SHRCorrectionType::QuadraticSHR: {
                if (lAlphaBlanks(AlphaNum)) {
                    ShowSevereEmptyField(state, eoh, cAlphaFieldNames(AlphaNum));
                    ErrorsFound = true;
                } else if ((WarehouseCoil(CoilID).SHRCorrectionCurvePtr = Curve::GetCurveIndex(state, Alphas(AlphaNum))) == 0) {
                    ShowSevereItemNotFound(state, eoh, cAlphaFieldNames(AlphaNum), Alphas(AlphaNum));
                    ErrorsFound = true;
                }
                // error checks for curve type entered and curve name
                ErrorsFound |= Curve::CheckCurveDims(state,
                                                     WarehouseCoil(CoilID).SHRCorrectionCurvePtr, // Curve index
                                                     {1},                                         // Valid dimensions
                                                     RoutineName,                                 // Routine name
                                                     CurrentModuleObject,                         // Object Type
                                                     WarehouseCoil(CoilID).Name,                  // Object Name
                                                     cAlphaFieldNames(AlphaNum));                 // Field Name
            } break;
            case SHRCorrectionType::TabularRH_DT1_TRoom: {
                WarehouseCoil(CoilID).SHRCorrectionCurvePtr = Curve::GetCurveIndex(state, Alphas(AlphaNum)); // convert curve name to number
                if (lAlphaBlanks(AlphaNum)) {
                    ShowSevereError(state,
                                    format("{}{}=\"{}\", invalid  {} is blank, required.",
                                           RoutineName,
                                           CurrentModuleObject,
                                           WarehouseCoil(CoilID).Name,
                                           cAlphaFieldNames(AlphaNum)));
                    ErrorsFound = true;
                } else if (WarehouseCoil(CoilID).SHRCorrectionCurvePtr == 0) {
                    ShowSevereError(state, format("{}{}=\"{}\", invalid  ", RoutineName, CurrentModuleObject, WarehouseCoil(CoilID).Name));
                    ShowContinueError(state, format("...invalid curve {}=\"{}\".", cAlphaFieldNames(AlphaNum), Alphas(AlphaNum)));
                    ErrorsFound = true;
                }
                ErrorsFound |= Curve::CheckCurveDims(state,
                                                     WarehouseCoil(CoilID).SHRCorrectionCurvePtr, // Curve index
                                                     {3},                                         // Valid dimensions
                                                     RoutineName,                                 // Routine name
                                                     CurrentModuleObject,                         // Object Type
                                                     WarehouseCoil(CoilID).Name,                  // Object Name
                                                     cAlphaFieldNames(AlphaNum));                 // Field Name
                //        IF(WarehouseCoil(CoilID)%SHRCorrectionCurvePtr == 0) THEN
                //          CALL ShowSevereError(state, RoutineName//TRIM(CurrentModuleObject)//'="'//TRIM(WarehouseCoil(CoilID)%Name)//&
                //                           '", not found  '//TRIM(cAlphaFieldNames(AlphaNum)))
                //          ErrorsFound = .TRUE.
                //        END IF !valid table name
            } break;
            default:
                break;
            } // SHRCorrectionType

            ++NumNum; // N10
            if (!lNumericBlanks(NumNum)) {
                WarehouseCoil(CoilID).HeaterPower = Numbers(NumNum);
            } else {
                ShowSevereEmptyField(state, eoh, cNumericFieldNames(NumNum));
                ErrorsFound = true;
            }

            ++AlphaNum; // A6
            if (lAlphaBlanks(AlphaNum)) {
                WarehouseCoil(CoilID).heaterAvailSched = Sched::GetScheduleAlwaysOn(state);
            } else if ((WarehouseCoil(CoilID).heaterAvailSched = Sched::GetSchedule(state, Alphas(AlphaNum))) == nullptr) {
                ShowSevereItemNotFound(state, eoh, cAlphaFieldNames(AlphaNum), Alphas(AlphaNum));
                ErrorsFound = true;
            } else if (!WarehouseCoil(CoilID).heaterAvailSched->checkMinMaxVals(state, Clusive::In, 0.0, Clusive::In, 1.0)) {
                Sched::ShowSevereBadMinMax(state, eoh, cAlphaFieldNames(AlphaNum), Alphas(AlphaNum), Clusive::In, 0.0, Clusive::In, 1.0);
                ErrorsFound = true;
            }

            // Input fan control type
            ++AlphaNum; // A7
            if (lAlphaBlanks(AlphaNum)) {
                WarehouseCoil(CoilID).FanType = FanSpeedCtrlType::ConstantSpeed;
            } else if ((WarehouseCoil(CoilID).FanType = static_cast<FanSpeedCtrlType>(getEnumValue(fanSpeedCtrlTypeNamesUC, Alphas(AlphaNum)))) ==
                       FanSpeedCtrlType::Invalid) {
                ShowSevereInvalidKey(state, eoh, cAlphaFieldNames(AlphaNum), Alphas(AlphaNum));
                ErrorsFound = true;
            } // fan control type

            ++NumNum; // N11
            if (!lNumericBlanks(NumNum) && Numbers(NumNum) > 0.0) {
                WarehouseCoil(CoilID).RatedFanPower = Numbers(NumNum);
            } else {
                ShowSevereError(state,
                                format("{}{}=\"{}\", {} was not input or was less than 0 ",
                                       RoutineName,
                                       CurrentModuleObject,
                                       WarehouseCoil(CoilID).Name,
                                       cNumericFieldNames(NumNum)));
                ErrorsFound = true;
            } // coil fan power

            ++NumNum; // N12
            if (!lNumericBlanks(NumNum) && Numbers(NumNum) > 0.0) {
                WarehouseCoil(CoilID).RatedAirVolumeFlow = Numbers(NumNum);
            } else {
                ShowSevereError(state,
                                format("{}{}=\"{}\", {} is required and was not input or was less than 0  ",
                                       RoutineName,
                                       CurrentModuleObject,
                                       WarehouseCoil(CoilID).Name,
                                       cNumericFieldNames(NumNum)));
            } // air volume flow

            ++NumNum;                                       // N13
            WarehouseCoil(CoilID).FanMinAirFlowRatio = 0.2; // default value
            if (!lNumericBlanks(NumNum) && Numbers(NumNum) > 0.0) {
                WarehouseCoil(CoilID).FanMinAirFlowRatio = Numbers(NumNum);
            }

            // Input defrost type
            ++AlphaNum; // A8
            if (lAlphaBlanks(AlphaNum)) {
                WarehouseCoil(CoilID).defrostType = DefrostType::Elec;
            } else if ((WarehouseCoil(CoilID).defrostType = static_cast<DefrostType>(getEnumValue(defrostTypeNamesUC, Alphas(AlphaNum)))) ==
                       DefrostType::Invalid) {
                ShowSevereInvalidKey(state, eoh, cAlphaFieldNames(AlphaNum), Alphas(AlphaNum));
                ErrorsFound = true;
            } // defrost type

            ++AlphaNum; // A9
            if (lAlphaBlanks(AlphaNum)) {
                WarehouseCoil(CoilID).DefrostControlType = DefrostCtrlType::Sched;
            } else if ((WarehouseCoil(CoilID).DefrostControlType =
                            static_cast<DefrostCtrlType>(getEnumValue(defrostCtrlTypeNamesUC, Alphas(AlphaNum)))) == DefrostCtrlType::Invalid) {
                ShowSevereInvalidKey(state, eoh, cAlphaFieldNames(AlphaNum), Alphas(AlphaNum));
                ErrorsFound = true;
            } // defrost control type

            // convert defrost schedule name to pointer
            ++AlphaNum; // A10
            if (lAlphaBlanks(AlphaNum)) {
                ShowSevereEmptyField(state, eoh, cAlphaFieldNames(AlphaNum));
                ErrorsFound = true;
            } else if ((WarehouseCoil(CoilID).defrostSched = Sched::GetSchedule(state, Alphas(AlphaNum))) == nullptr) {
                ShowSevereItemNotFound(state, eoh, cAlphaFieldNames(AlphaNum), Alphas(AlphaNum));
                ErrorsFound = true;
            } else if (!WarehouseCoil(CoilID).defrostSched->checkMinMaxVals(state, Clusive::In, 0.0, Clusive::In, 1.0)) {
                Sched::ShowSevereBadMinMax(state, eoh, cAlphaFieldNames(AlphaNum), Alphas(AlphaNum), Clusive::In, 0.0, Clusive::In, 1.0);
                ErrorsFound = true;
            } // check for valid schedule name

            // convert defrost drip-down schedule name to pointer
            // some defrost types do not use drip-down schedules, use same defrost schedule pointer in that case
            ++AlphaNum; // A11
            if (lAlphaBlanks(AlphaNum)) {
                WarehouseCoil(CoilID).defrostDripDownSched = WarehouseCoil(CoilID).defrostSched;
            } else if ((WarehouseCoil(CoilID).defrostDripDownSched = Sched::GetSchedule(state, Alphas(AlphaNum))) == nullptr) {
                ShowSevereItemNotFound(state, eoh, cAlphaFieldNames(AlphaNum), Alphas(AlphaNum));
                ErrorsFound = true;
            } else if (!WarehouseCoil(CoilID).defrostDripDownSched->checkMinMaxVals(state, Clusive::In, 0.0, Clusive::In, 1.0)) {
                Sched::ShowSevereBadMinMax(state, eoh, cAlphaFieldNames(AlphaNum), Alphas(AlphaNum), Clusive::In, 0.0, Clusive::In, 1.0);
                ErrorsFound = true;
            } // check for valid schedule name

            ++NumNum; // N14
            if (WarehouseCoil(CoilID).defrostType == DefrostType::OffCycle || WarehouseCoil(CoilID).defrostType == DefrostType::None) {
                WarehouseCoil(CoilID).DefrostCapacity = 0.0;
                // Don't even need to read Defrost capacity for those two defrost types.
            } else { // have electric or hot gas/brine defrost
                if ((lNumericBlanks(NumNum)) || (Numbers(NumNum) <= 0.0)) {
                    ShowSevereError(state,
                                    format("{}{}=\"{}\", {} must be input and greater than or equal to 0 W for {} {}",
                                           RoutineName,
                                           CurrentModuleObject,
                                           WarehouseCoil(CoilID).Name,
                                           cNumericFieldNames(NumNum),
                                           cAlphaFieldNames(AlphaNum),
                                           Alphas(AlphaNum)));
                    ErrorsFound = true;
                } else {
                    WarehouseCoil(CoilID).DefrostCapacity = Numbers(NumNum);
                } // Blank  or negative Defrost Capacity

                // defaults for defrost energy fraction are 0.7 for elec defrost and 0.3 for warm fluid
                // note this value is only used for temperature terminated defrost control type
                if (WarehouseCoil(CoilID).defrostType == DefrostType::Elec) {
                    WarehouseCoil(CoilID).DefEnergyFraction = 0.7;
                }
                if (WarehouseCoil(CoilID).defrostType == DefrostType::Fluid) {
                    WarehouseCoil(CoilID).DefEnergyFraction = 0.3;
                }

                ++NumNum; // N15
                if (!lNumericBlanks(NumNum)) {
                    if ((Numbers(NumNum) > 1.0) || (Numbers(NumNum) < 0.0)) {
                        ShowWarningError(state,
                                         format("{}{}=\"{}\", {} must be between 0 and 1, default values will be used.",
                                                RoutineName,
                                                CurrentModuleObject,
                                                WarehouseCoil(CoilID).Name,
                                                cNumericFieldNames(NumNum)));
                    } else {
                        WarehouseCoil(CoilID).DefEnergyFraction = Numbers(NumNum);
                    } // number out of range
                } // lnumericblanks
            } // defrost type

            ++AlphaNum; // A12
            if (lAlphaBlanks(AlphaNum)) {
                WarehouseCoil(CoilID).VerticalLocation = VerticalLoc::Middle; // default position
            } else if ((WarehouseCoil(CoilID).VerticalLocation = static_cast<VerticalLoc>(getEnumValue(verticalLocNamesUC, Alphas(AlphaNum)))) ==
                       VerticalLoc::Invalid) {
                ShowSevereInvalidKey(state, eoh, cAlphaFieldNames(AlphaNum), Alphas(AlphaNum));
                ErrorsFound = true;
            } // Vertical location class

            ++NumNum; // N16
            WarehouseCoil(CoilID).DesignRefrigInventory = 0.0;
            if (!lNumericBlanks(NumNum)) {
                WarehouseCoil(CoilID).DesignRefrigInventory = Numbers(NumNum);
            }
        } // NumRefrigAirChillers
    } // NumRefrigerationAirChillers > 0

    //************ START Warehouse Coil SET INPUT **************
    // One Set allowed per zone, but indiv coils within zone can be served by different compressor/condenser systems

    if (state.dataRefrigCase->NumRefrigChillerSets > 0) {

        state.dataRefrigCase->CheckChillerSetName.dimension(state.dataRefrigCase->NumRefrigChillerSets, true);

        CurrentModuleObject = "ZoneHVAC:RefrigerationChillerSet";
        for (int SetID = 1; SetID <= state.dataRefrigCase->NumRefrigChillerSets; ++SetID) {
            state.dataInputProcessing->inputProcessor->getObjectItem(state,
                                                                     CurrentModuleObject,
                                                                     SetID,
                                                                     Alphas,
                                                                     NumAlphas,
                                                                     Numbers,
                                                                     NumNumbers,
                                                                     IOStatus,
                                                                     lNumericBlanks,
                                                                     lAlphaBlanks,
                                                                     cAlphaFieldNames,
                                                                     cNumericFieldNames);

            ErrorObjectHeader eoh{routineName, CurrentModuleObject, Alphas(1)};

            AlphaNum = 1;
            Util::IsNameEmpty(state, Alphas(1), CurrentModuleObject, ErrorsFound);

            AirChillerSet(SetID).Name = Alphas(AlphaNum);

            AlphaNum = 2;
            if (lAlphaBlanks(AlphaNum)) {
                AirChillerSet(SetID).availSched = Sched::GetScheduleAlwaysOn(state);
            } else if ((AirChillerSet(SetID).availSched = Sched::GetSchedule(state, Alphas(AlphaNum))) == nullptr) {
                ShowSevereItemNotFound(state, eoh, cAlphaFieldNames(AlphaNum), Alphas(AlphaNum));
                ErrorsFound = true;
            } else if (!AirChillerSet(SetID).availSched->checkMinMaxVals(state, Clusive::In, 0.0, Clusive::In, 1.0)) {
                Sched::ShowSevereBadMinMax(state, eoh, cAlphaFieldNames(AlphaNum), Alphas(AlphaNum), Clusive::In, 0.0, Clusive::In, 1.0);
                ErrorsFound = true;
            }

            ++AlphaNum;
            AirChillerSet(SetID).ZoneName = Alphas(AlphaNum);
            AirChillerSet(SetID).ZoneNum = Util::FindItemInList(Alphas(AlphaNum), state.dataHeatBal->Zone);

            if (AirChillerSet(SetID).ZoneNum == 0) {
                ShowSevereError(state,
                                format("{}{}=\"{}\", invalid  {} not valid: {}",
                                       RoutineName,
                                       CurrentModuleObject,
                                       AirChillerSet(SetID).Name,
                                       cAlphaFieldNames(AlphaNum),
                                       Alphas(AlphaNum)));
                ErrorsFound = true;
            }
            AirChillerSet(SetID).ZoneNodeNum = DataZoneEquipment::GetSystemNodeNumberForZone(state, AirChillerSet(SetID).ZoneNum);
            if (AirChillerSet(SetID).ZoneNodeNum == 0) {
                ShowSevereError(state,
                                format("{}{}=\"{}\" System Node Number not found for {} = {}",
                                       RoutineName,
                                       CurrentModuleObject,
                                       AirChillerSet(SetID).Name,
                                       cAlphaFieldNames(AlphaNum),
                                       Alphas(AlphaNum)));
                ShowContinueError(state,
                                  ".. Refrigeration chillers must reference a controlled Zone (appear in a ZoneHVAC:EquipmentConnections object.");
                ErrorsFound = true;
            }
            state.dataRefrigCase->RefrigPresentInZone(AirChillerSet(SetID).ZoneNum) = true;

            ++AlphaNum;
            if (!lAlphaBlanks(AlphaNum)) {
                ShowMessage(state,
                            format("{}{}=\"{}\" {} is not used. This is not an error.  Energy is exchanged directly with the zone independent of "
                                   "any air system. ",
                                   RoutineName,
                                   CurrentModuleObject,
                                   AirChillerSet(SetID).Name,
                                   cAlphaFieldNames(AlphaNum)));
                // Node identification reserved for future use.  Currently exchange energy directly with zone outside any air system
                // AirChillerSet(SetID)%NodeNumInlet = &
                //       NodeInputManager::GetOnlySingleNode(state, Alphas(AlphaNum),ErrorsFound,TRIM(CurrentModuleObject), &
                //                    AirChillerSet(SetID)%Name,DataLoopNode::NodeFluidType::Air,DataLoopNode::NodeConnectionType::Inlet,1,DataLoopNode::ObjectIsNotParent)
            }

            ++AlphaNum;
            if (!lAlphaBlanks(AlphaNum)) {
                ShowMessage(state,
                            format("{}{}=\"{}\" {} is not used. This is not an error.  Energy is exchanged directly with the zone independent of "
                                   "any air system. ",
                                   RoutineName,
                                   CurrentModuleObject,
                                   AirChillerSet(SetID).Name,
                                   cAlphaFieldNames(AlphaNum)));
                // Node identification reserved for future use.  Currently exchange energy directly with zone outside any air system
                // AirChillerSet(SetID)%NodeNumOutlet = &
                //         NodeInputManager::GetOnlySingleNode(state, Alphas(AlphaNum),ErrorsFound,TRIM(CurrentModuleObject), &
                //                      AirChillerSet(SetID)%Name,DataLoopNode::NodeFluidType::Air,DataLoopNode::NodeConnectionType::Outlet,1,DataLoopNode::ObjectIsNotParent)
            }

            // An extensible list is used to enter the individual names of each chiller in the set.
            // These chillers will be dispatched in this list order to meet the required zone load
            int NumChillersInSet = NumAlphas - AlphaNum;
            int AlphaStartList = AlphaNum; //+ 1
            AirChillerSet(SetID).NumCoils = NumChillersInSet;
            if (!allocated(AirChillerSet(SetID).CoilNum)) {
                AirChillerSet(SetID).CoilNum.allocate(NumChillersInSet);
            }
            for (int ChillerIndex = 1; ChillerIndex <= NumChillersInSet; ++ChillerIndex) {
                int AlphaListNum = AlphaStartList + ChillerIndex;
                if (!lAlphaBlanks(AlphaListNum)) {
                    int CoilNum = Util::FindItemInList(Alphas(AlphaListNum), WarehouseCoil);
                    if (CoilNum == 0) {
                        ShowSevereError(state,
                                        format("{}{}=\"{}\", has an invalid {} defined as {}",
                                               RoutineName,
                                               CurrentModuleObject,
                                               AirChillerSet(SetID).Name,
                                               cAlphaFieldNames(AlphaListNum),
                                               Alphas(AlphaListNum)));
                        ErrorsFound = true;
                    } // == 0
                    AirChillerSet(SetID).CoilNum(ChillerIndex) = CoilNum;
                    WarehouseCoil(CoilNum).ZoneName = AirChillerSet(SetID).ZoneName;
                    WarehouseCoil(CoilNum).ZoneNum = AirChillerSet(SetID).ZoneNum;
                    WarehouseCoil(CoilNum).ZoneNodeNum = AirChillerSet(SetID).ZoneNodeNum;
                } // ! = alphablanks
            } // CoilID over NumChillersInSet
        } // NumChillerSets
    } // NumChillerSets > 0
    //************* End Air Chiller Sets

    //**** Read CaseAndWalkIn Lists **********************************************************
    if (state.dataRefrigCase->NumSimulationCaseAndWalkInLists > 0) {
        CurrentModuleObject = "Refrigeration:CaseAndWalkInList";
        for (int ListNum = 1; ListNum <= state.dataRefrigCase->NumSimulationCaseAndWalkInLists; ++ListNum) {
            state.dataInputProcessing->inputProcessor->getObjectItem(state,
                                                                     CurrentModuleObject,
                                                                     ListNum,
                                                                     Alphas,
                                                                     NumAlphas,
                                                                     Numbers,
                                                                     NumNumbers,
                                                                     IOStatus,
                                                                     lNumericBlanks,
                                                                     lAlphaBlanks,
                                                                     cAlphaFieldNames,
                                                                     cNumericFieldNames);
            Util::IsNameEmpty(state, Alphas(1), CurrentModuleObject, ErrorsFound);
            CaseAndWalkInList(ListNum).Name = Alphas(1);

            // CaseAndWalkInList alphas include CaseAndWalkInList name and one name for each Case or WalkIn in list
            // below allocates larger than needed (each allocated to sum of both), but avoids two loops through input fields
            int NumTotalLoadsOnList = NumAlphas - 1;
            if (!allocated(CaseAndWalkInList(ListNum).WalkInItemNum)) {
                CaseAndWalkInList(ListNum).WalkInItemNum.allocate(NumTotalLoadsOnList);
            }
            if (!allocated(CaseAndWalkInList(ListNum).CaseItemNum)) {
                CaseAndWalkInList(ListNum).CaseItemNum.allocate(NumTotalLoadsOnList);
            }
            if (!allocated(CaseAndWalkInList(ListNum).CoilItemNum)) {
                CaseAndWalkInList(ListNum).CoilItemNum.allocate(NumTotalLoadsOnList);
            }

            int NumCasesOnList = 0;
            int NumCoilsOnList = 0;
            int NumWalkInsOnList = 0;
            int LoadCount = 0;
            for (int NumLoad = 1; NumLoad <= NumTotalLoadsOnList; ++NumLoad) {
                int AlphaListNum = 1 + NumLoad;
                if (!lAlphaBlanks(AlphaListNum)) {
                    ++LoadCount;
                    int LoadWalkInNum = 0;
                    int LoadCaseNum = 0;
                    int LoadCoilNum = 0;
                    if (state.dataRefrigCase->NumSimulationWalkIns > 0) {
                        LoadWalkInNum = Util::FindItemInList(Alphas(AlphaListNum), WalkIn);
                    }
                    if (state.dataRefrigCase->NumSimulationCases > 0) {
                        LoadCaseNum = Util::FindItemInList(Alphas(AlphaListNum), RefrigCase);
                    }
                    if (state.dataRefrigCase->NumSimulationRefrigAirChillers > 0) {
                        LoadCoilNum = Util::FindItemInList(Alphas(AlphaListNum), WarehouseCoil);
                    }
                    if ((LoadWalkInNum == 0) && (LoadCaseNum == 0) && (LoadCoilNum == 0)) {
                        ShowSevereError(state,
                                        format("{}{}=\"{}\", has an invalid value of {}",
                                               RoutineName,
                                               CurrentModuleObject,
                                               cAlphaFieldNames(AlphaListNum),
                                               Alphas(AlphaListNum)));
                        ErrorsFound = true;
                    } else if ((LoadWalkInNum != 0) && (LoadCaseNum != 0) && (LoadCoilNum != 0)) {
                        ShowSevereError(state,
                                        format("{}{}=\"{}\", {} Case and WalkIns and Refrigerated Coils cannot have the same name.",
                                               RoutineName,
                                               CurrentModuleObject,
                                               cAlphaFieldNames(AlphaListNum),
                                               Alphas(AlphaListNum)));
                        ErrorsFound = true;
                    } else if (LoadWalkInNum != 0) {
                        ++NumWalkInsOnList;
                        CaseAndWalkInList(ListNum).WalkInItemNum(NumWalkInsOnList) = LoadWalkInNum;
                    } else if (LoadCaseNum != 0) {
                        ++NumCasesOnList;
                        CaseAndWalkInList(ListNum).CaseItemNum(NumCasesOnList) = LoadCaseNum;
                    } else if (LoadCoilNum != 0) {
                        ++NumCoilsOnList;
                        CaseAndWalkInList(ListNum).CoilItemNum(NumCoilsOnList) = LoadCoilNum;
                    }
                } // lAlphaBlanks
            } // Num Total Loads on List
            if (LoadCount == 0) {
                ShowSevereError(
                    state,
                    format(
                        "{}{}, \"{}\" : degenerate list All entries were blank.", RoutineName, CurrentModuleObject, CaseAndWalkInList(ListNum).Name));
                ErrorsFound = true;
            } // loadcount == 0
            CaseAndWalkInList(ListNum).NumCases = NumCasesOnList;
            CaseAndWalkInList(ListNum).NumCoils = NumCoilsOnList;
            CaseAndWalkInList(ListNum).NumWalkIns = NumWalkInsOnList;
        } // ListNum=1,NumSimulationCaseAndWalkInLists
    } //(NumSimulationCaseAndWalkInLists > 0)

    //**** End read CaseAndWalkIn Lists **********************************************************

    //************** Start RefrigerationRacks

    if (state.dataRefrigCase->NumRefrigeratedRacks > 0) {

        CurrentModuleObject = "Refrigeration:CompressorRack";

        for (int RackNum = 1; RackNum <= state.dataRefrigCase->NumRefrigeratedRacks; ++RackNum) {

            state.dataInputProcessing->inputProcessor->getObjectItem(state,
                                                                     CurrentModuleObject,
                                                                     RackNum,
                                                                     Alphas,
                                                                     NumAlphas,
                                                                     Numbers,
                                                                     NumNumbers,
                                                                     IOStatus,
                                                                     lNumericBlanks,
                                                                     lAlphaBlanks,
                                                                     cAlphaFieldNames,
                                                                     cNumericFieldNames);

            ErrorObjectHeader eoh{routineName, CurrentModuleObject, Alphas(1)};
            Util::IsNameEmpty(state, Alphas(1), CurrentModuleObject, ErrorsFound);

            RefrigRack(RackNum).Name = Alphas(1);
            RefrigRack(RackNum).MyIdx = RackNum;
            state.dataHeatBal->HeatReclaimRefrigeratedRack(RackNum).Name = Alphas(1);
            state.dataHeatBal->HeatReclaimRefrigeratedRack(RackNum).SourceType = CurrentModuleObject;

            if (lAlphaBlanks(2)) {
                RefrigRack(RackNum).HeatRejectionLocation = HeatRejLocation::Outdoors;
            } else if ((RefrigRack(RackNum).HeatRejectionLocation = static_cast<HeatRejLocation>(getEnumValue(heatRejLocationNamesUC, Alphas(2)))) ==
                       HeatRejLocation::Invalid) {
                RefrigRack(RackNum).HeatRejectionLocation = HeatRejLocation::Outdoors;
                ShowWarningInvalidKey(state, eoh, cAlphaFieldNames(2), Alphas(2), "Outdoors");
            }

            RefrigRack(RackNum).RatedCOP = Numbers(1);

            if (RefrigRack(RackNum).RatedCOP <= 0.0) {
                ShowSevereError(state,
                                format("{}{}=\"{}\" {} must be greater than 0.0",
                                       RoutineName,
                                       CurrentModuleObject,
                                       RefrigRack(RackNum).Name,
                                       cNumericFieldNames(1)));
                ErrorsFound = true;
            }

            RefrigRack(RackNum).COPFTempPtr = Curve::GetCurveIndex(state, Alphas(3)); // convert curve name to number
            if (RefrigRack(RackNum).COPFTempPtr == 0) {
                ShowSevereItemNotFound(state, eoh, cAlphaFieldNames(3), Alphas(3));
                ErrorsFound = true;
            }

            ErrorsFound |= Curve::CheckCurveDims(state,
                                                 RefrigRack(RackNum).COPFTempPtr, // Curve index
                                                 {1},                             // Valid dimensions
                                                 RoutineName,                     // Routine name
                                                 CurrentModuleObject,             // Object Type
                                                 RefrigRack(RackNum).Name,        // Object Name
                                                 cAlphaFieldNames(3));            // Field Name

            RefrigRack(RackNum).CondenserFanPower = Numbers(2);
            if (Numbers(2) < 0.0) {
                ShowSevereError(state,
                                format("{}{}=\"{}\" {} must be greater than or equal to 0 Watts.",
                                       RoutineName,
                                       CurrentModuleObject,
                                       RefrigRack(RackNum).Name,
                                       cNumericFieldNames(2)));
                ErrorsFound = true;
            }

            RefrigRack(RackNum).TotCondFTempPtr = Curve::GetCurveIndex(state, Alphas(4)); // convert curve name to number
            if ((!lAlphaBlanks(4)) && RefrigRack(RackNum).TotCondFTempPtr == 0) {
                ShowSevereError(state,
                                format("{}{}=\"{}\", invalid  {} not found:{}",
                                       RoutineName,
                                       CurrentModuleObject,
                                       RefrigRack(RackNum).Name,
                                       cAlphaFieldNames(4),
                                       Alphas(4)));
                ErrorsFound = true;
            }

            if (!lAlphaBlanks(4)) {
                ErrorsFound |= Curve::CheckCurveDims(state,
                                                     RefrigRack(RackNum).TotCondFTempPtr, // Curve index
                                                     {1},                                 // Valid dimensions
                                                     RoutineName,                         // Routine name
                                                     CurrentModuleObject,                 // Object Type
                                                     RefrigRack(RackNum).Name,            // Object Name
                                                     cAlphaFieldNames(4));                // Field Name
            }

            if (lAlphaBlanks(5)) {
                RefrigRack(RackNum).CondenserType = DataHeatBalance::RefrigCondenserType::Air;
            } else if ((RefrigRack(RackNum).CondenserType = static_cast<DataHeatBalance::RefrigCondenserType>(
                            getEnumValue(DataHeatBalance::refrigCondenserTypeNamesUC, Alphas(5)))) == DataHeatBalance::RefrigCondenserType::Invalid) {
                ShowSevereInvalidKey(state, eoh, cAlphaFieldNames(5), Alphas(5));
                ErrorsFound = true;
            } else if (RefrigRack(RackNum).CondenserType == DataHeatBalance::RefrigCondenserType::Evap ||
                       RefrigRack(RackNum).CondenserType == DataHeatBalance::RefrigCondenserType::Water) {
                if (RefrigRack(RackNum).HeatRejectionLocation == HeatRejLocation::Zone) {
                    ShowWarningError(state,
                                     format("{}=\"{}\" {}=\"{}\" not available with {} = Zone.",
                                            CurrentModuleObject,
                                            RefrigRack(RackNum).Name,
                                            cAlphaFieldNames(5),
                                            Alphas(5),
                                            cAlphaFieldNames(2)));
                    ShowContinueError(state, format("{} reset to Air Cooled and simulation continues.", cAlphaFieldNames(5)));
                    RefrigRack(RackNum).CondenserType = DataHeatBalance::RefrigCondenserType::Air;
                }
            } else if (RefrigRack(RackNum).CondenserType == DataHeatBalance::RefrigCondenserType::Cascade ||
                       RefrigRack(RackNum).CondenserType == DataHeatBalance::RefrigCondenserType::WaterHeater) {
                ShowSevereInvalidKey(state, eoh, cAlphaFieldNames(5), Alphas(5));
                ErrorsFound = true;
            }
            // Get water-cooled condenser input, if applicable
            if (RefrigRack(RackNum).CondenserType == DataHeatBalance::RefrigCondenserType::Water) {
                RefrigRack(RackNum).InletNode = NodeInputManager::GetOnlySingleNode(state,
                                                                                    Alphas(6),
                                                                                    ErrorsFound,
                                                                                    DataLoopNode::ConnectionObjectType::RefrigerationCompressorRack,
                                                                                    Alphas(1),
                                                                                    DataLoopNode::NodeFluidType::Water,
                                                                                    DataLoopNode::ConnectionType::Inlet,
                                                                                    NodeInputManager::CompFluidStream::Primary,
                                                                                    DataLoopNode::ObjectIsNotParent);
                RefrigRack(RackNum).OutletNode = NodeInputManager::GetOnlySingleNode(state,
                                                                                     Alphas(7),
                                                                                     ErrorsFound,
                                                                                     DataLoopNode::ConnectionObjectType::RefrigerationCompressorRack,
                                                                                     Alphas(1),
                                                                                     DataLoopNode::NodeFluidType::Water,
                                                                                     DataLoopNode::ConnectionType::Outlet,
                                                                                     NodeInputManager::CompFluidStream::Primary,
                                                                                     DataLoopNode::ObjectIsNotParent);
                // Check node connections
                BranchNodeConnections::TestCompSet(state, CurrentModuleObject, Alphas(1), Alphas(6), Alphas(7), "RefrigRack Nodes");
                // Get loop flow type
                if ((RefrigRack(RackNum).FlowType = static_cast<CndsrFlowType>(getEnumValue(cndsrFlowTypeNamesUC, Alphas(8)))) ==
                    CndsrFlowType::Invalid) {
                    ShowSevereInvalidKey(state, eoh, cAlphaFieldNames(8), Alphas(8));
                    ErrorsFound = true;
                }
                // Get outlet temperature schedule for variable flow case
                if (RefrigRack(RackNum).FlowType == CndsrFlowType::Variable) {
                    if (lAlphaBlanks(9)) {
                    } else if ((RefrigRack(RackNum).outletTempSched = Sched::GetSchedule(state, Alphas(9))) == nullptr) {
                        ShowSevereItemNotFound(state, eoh, cAlphaFieldNames(9), Alphas(9));
                        ErrorsFound = true;
                    }
                }

                // Get volumetric flow rate if applicable
                if (RefrigRack(RackNum).FlowType == CndsrFlowType::Constant) {
                    RefrigRack(RackNum).DesVolFlowRate = Numbers(3);
                    RefrigRack(RackNum).VolFlowRate = Numbers(3);
                }
                // Get maximum flow rates
                RefrigRack(RackNum).VolFlowRateMax = Numbers(4);

                // Check constant flow for max violation, if applicable
                if (RefrigRack(RackNum).FlowType == CndsrFlowType::Constant && RefrigRack(RackNum).VolFlowRate > Numbers(4)) {
                    ShowSevereError(state,
                                    format("{}{}=\"{}\" {} > {}.",
                                           RoutineName,
                                           CurrentModuleObject,
                                           RefrigRack(RackNum).Name,
                                           cNumericFieldNames(3),
                                           cNumericFieldNames(4)));
                    ShowContinueError(state, "Revise flow rates.");
                    ErrorsFound = true;
                }
                // Get max/min allowed water temps
                RefrigRack(RackNum).OutletTempMax = Numbers(5);
                RefrigRack(RackNum).InletTempMin = Numbers(6);
                // set flow request for plant sizing.
                PlantUtilities::RegisterPlantCompDesignFlow(state, RefrigRack(RackNum).InletNode, RefrigRack(RackNum).VolFlowRateMax);
            } // Water cooled condenser data

            // Get evaporative cooled condenser input
            if (lAlphaBlanks(10)) {
            } else if ((RefrigRack(RackNum).evapAvailSched = Sched::GetSchedule(state, Alphas(10))) == nullptr) {
                ShowSevereItemNotFound(state, eoh, cAlphaFieldNames(10), Alphas(10));
                ErrorsFound = true;
            } else if (!RefrigRack(RackNum).evapAvailSched->checkMinVal(state, Clusive::In, 0.0)) {
                Sched::ShowSevereBadMin(state, eoh, cAlphaFieldNames(10), Alphas(10), Clusive::In, 0.0);
                ErrorsFound = true;
            }

            RefrigRack(RackNum).EvapEffect = Numbers(7);
            if (RefrigRack(RackNum).EvapEffect < 0.0 || RefrigRack(RackNum).EvapEffect > 1.0) {
                ShowSevereError(state,
                                format("{}{}=\"{}\" {} cannot be less than zero or greater than 1.0.",
                                       RoutineName,
                                       CurrentModuleObject,
                                       RefrigRack(RackNum).Name,
                                       cNumericFieldNames(7)));
                ErrorsFound = true;
            }

            RefrigRack(RackNum).CondenserAirFlowRate = Numbers(8);
            if (RefrigRack(RackNum).CondenserType == DataHeatBalance::RefrigCondenserType::Evap && RefrigRack(RackNum).CondenserAirFlowRate <= 0.0 &&
                RefrigRack(RackNum).CondenserAirFlowRate != Constant::AutoCalculate) {
                ShowSevereError(state,
                                format("{}{}=\"{}\", {} cannot be less than or equal to zero.",
                                       RoutineName,
                                       CurrentModuleObject,
                                       RefrigRack(RackNum).Name,
                                       cNumericFieldNames(8)));
                ErrorsFound = true;
            }

            //   Basin heater power as a function of temperature must be greater than or equal to 0
            RefrigRack(RackNum).BasinHeaterPowerFTempDiff = Numbers(9);
            if (RefrigRack(RackNum).CondenserType == DataHeatBalance::RefrigCondenserType::Evap && Numbers(9) < 0.0) {
                ShowSevereError(
                    state, format("{}{}=\"{}\", {} must be >= 0", RoutineName, CurrentModuleObject, RefrigRack(RackNum).Name, cNumericFieldNames(9)));
                ErrorsFound = true;
            }

            RefrigRack(RackNum).BasinHeaterSetPointTemp = Numbers(10);
            if (RefrigRack(RackNum).CondenserType == DataHeatBalance::RefrigCondenserType::Evap &&
                RefrigRack(RackNum).BasinHeaterSetPointTemp < 2.0) {
                ShowWarningError(state,
                                 format("{}=\"{}\", {} is less than 2 deg C. Freezing could occur.",
                                        CurrentModuleObject,
                                        RefrigRack(RackNum).Name,
                                        cNumericFieldNames(10)));
            }

            RefrigRack(RackNum).EvapPumpPower = Numbers(11);
            if (RefrigRack(RackNum).CondenserType == DataHeatBalance::RefrigCondenserType::Evap && RefrigRack(RackNum).EvapPumpPower < 0.0 &&
                RefrigRack(RackNum).EvapPumpPower != Constant::AutoCalculate) {
                ShowSevereError(state,
                                format("{}{}=\"{}\", {} cannot be less than zero.",
                                       RoutineName,
                                       CurrentModuleObject,
                                       RefrigRack(RackNum).Name,
                                       cNumericFieldNames(11)));
                ErrorsFound = true;
            }

            // Get Water System tank connections
            RefrigRack(RackNum).SupplyTankName = Alphas(11);
            if (lAlphaBlanks(11)) {
                RefrigRack(RackNum).EvapWaterSupplyMode = WaterSupply::FromMains;
            } else {
                RefrigRack(RackNum).EvapWaterSupplyMode = WaterSupply::FromTank;
                WaterManager::SetupTankDemandComponent(state,
                                                       RefrigRack(RackNum).Name,
                                                       CurrentModuleObject,
                                                       RefrigRack(RackNum).SupplyTankName,
                                                       ErrorsFound,
                                                       RefrigRack(RackNum).EvapWaterSupTankID,
                                                       RefrigRack(RackNum).EvapWaterTankDemandARRID);
            }

            // Check condenser air inlet node connection
            if (lAlphaBlanks(12)) {
                RefrigRack(RackNum).OutsideAirNodeNum = 0;
            } else {
                RefrigRack(RackNum).OutsideAirNodeNum =
                    NodeInputManager::GetOnlySingleNode(state,
                                                        Alphas(12),
                                                        ErrorsFound,
                                                        DataLoopNode::ConnectionObjectType::RefrigerationCompressorRack,
                                                        Alphas(1),
                                                        DataLoopNode::NodeFluidType::Air,
                                                        DataLoopNode::ConnectionType::OutsideAirReference,
                                                        NodeInputManager::CompFluidStream::Primary,
                                                        DataLoopNode::ObjectIsParent);
                if (!OutAirNodeManager::CheckOutAirNodeNumber(state, RefrigRack(RackNum).OutsideAirNodeNum)) {
                    ShowSevereError(state,
                                    format("{}{}=\"{}\", {} not found: {}",
                                           RoutineName,
                                           CurrentModuleObject,
                                           RefrigRack(RackNum).Name,
                                           cAlphaFieldNames(12),
                                           Alphas(12)));
                    ShowContinueError(state, "...does not appear in an OutdoorAir:NodeList or as an OutdoorAir:Node.");
                    ErrorsFound = true;
                }
            }

            if (!lAlphaBlanks(13)) {
                RefrigRack(RackNum).EndUseSubcategory = Alphas(13);
            }

            // Read all loads on this rack: cases and walk-ins and coils
            NumCases = 0;
            int NumCoils = 0;
            NumWalkIns = 0;
            RefrigRack(RackNum).NumCases = 0;
            RefrigRack(RackNum).NumCoils = 0;
            RefrigRack(RackNum).NumWalkIns = 0;
            RefrigRack(RackNum).TotalRackLoad = 0.0;

            //   Read display case and walkin assignments for this rack
            AlphaNum = 14;
            if (lAlphaBlanks(AlphaNum)) {
                // No cases or walkins or coils specified, ie, rack has no load
                ShowSevereError(state,
                                format("{}{}=\"{}\" : has no loads, must have at least one of: {}",
                                       RoutineName,
                                       CurrentModuleObject,
                                       RefrigRack(RackNum).Name,
                                       cAlphaFieldNames(14)));
                ErrorsFound = true;
            } else { // (.NOT. lAlphaBlanks(AlphaNum))
                // Entry for Alphas(AlphaNum) can be either a Case, WalkIn, Coil, or CaseAndWalkInList name
                int CaseAndWalkInListNum = 0;
                int CaseNum = 0;
                int WalkInNum = 0;
                int CoilNum = 0;
                if (state.dataRefrigCase->NumSimulationCaseAndWalkInLists > 0) {
                    CaseAndWalkInListNum = Util::FindItemInList(Alphas(AlphaNum), CaseAndWalkInList);
                }
                if (state.dataRefrigCase->NumSimulationCases > 0) {
                    CaseNum = Util::FindItemInList(Alphas(AlphaNum), RefrigCase);
                }
                if (state.dataRefrigCase->NumSimulationWalkIns > 0) {
                    WalkInNum = Util::FindItemInList(Alphas(AlphaNum), WalkIn);
                }
                if (state.dataRefrigCase->NumSimulationRefrigAirChillers > 0) {
                    CoilNum = Util::FindItemInList(Alphas(AlphaNum), WarehouseCoil);
                }
                int NumNameMatches = 0;
                if (CaseAndWalkInListNum != 0) {
                    ++NumNameMatches;
                }
                if (CaseNum != 0) {
                    ++NumNameMatches;
                }
                if (WalkInNum != 0) {
                    ++NumNameMatches;
                }
                if (CoilNum != 0) {
                    ++NumNameMatches;
                }

                if (NumNameMatches != 1) { // name must uniquely point to a list or a single case or walkin
                    ErrorsFound = true;
                    if (NumNameMatches == 0) {
                        ShowSevereError(state,
                                        format("{}{}=\"{}\" : has an invalid {}: {}",
                                               RoutineName,
                                               CurrentModuleObject,
                                               RefrigRack(RackNum).Name,
                                               cAlphaFieldNames(AlphaNum),
                                               Alphas(AlphaNum)));
                    } else if (NumNameMatches > 1) {
                        ShowSevereError(state,
                                        format("{}{}=\"{}\" : has a non-unique name that could be either a {}: {}",
                                               RoutineName,
                                               CurrentModuleObject,
                                               RefrigRack(RackNum).Name,
                                               cAlphaFieldNames(AlphaNum),
                                               Alphas(AlphaNum)));
                    } // num matches = 0 or > 1
                } else if (CaseAndWalkInListNum != 0) { // Name points to a CaseAndWalkInList
                    NumCoils = CaseAndWalkInList(CaseAndWalkInListNum).NumCoils;
                    NumCases = CaseAndWalkInList(CaseAndWalkInListNum).NumCases;
                    NumWalkIns = CaseAndWalkInList(CaseAndWalkInListNum).NumWalkIns;
                    RefrigRack(RackNum).NumCoils = NumCoils;
                    RefrigRack(RackNum).NumCases = NumCases;
                    RefrigRack(RackNum).NumWalkIns = NumWalkIns;
                    if (!allocated(RefrigRack(RackNum).CoilNum)) {
                        RefrigRack(RackNum).CoilNum.allocate(NumCoils);
                    }
                    RefrigRack(RackNum).CoilNum({1, NumCoils}) = CaseAndWalkInList(CaseAndWalkInListNum).CoilItemNum({1, NumCoils});
                    if (!allocated(RefrigRack(RackNum).CaseNum)) {
                        RefrigRack(RackNum).CaseNum.allocate(NumCases);
                    }
                    RefrigRack(RackNum).CaseNum({1, NumCases}) = CaseAndWalkInList(CaseAndWalkInListNum).CaseItemNum({1, NumCases});
                    if (!allocated(RefrigRack(RackNum).WalkInNum)) {
                        RefrigRack(RackNum).WalkInNum.allocate(NumWalkIns);
                    }
                    RefrigRack(RackNum).WalkInNum({1, NumWalkIns}) = CaseAndWalkInList(CaseAndWalkInListNum).WalkInItemNum({1, NumWalkIns});
                } else if (CoilNum != 0) { // Name points to a coil
                    NumCoils = 1;
                    RefrigRack(RackNum).NumCoils = 1;
                    if (!allocated(RefrigRack(RackNum).CoilNum)) {
                        RefrigRack(RackNum).CoilNum.allocate(NumCoils);
                    }
                    RefrigRack(RackNum).CoilNum(NumCoils) = CoilNum;
                } else if (CaseNum != 0) { // Name points to a case
                    NumCases = 1;
                    RefrigRack(RackNum).NumCases = 1;
                    if (!allocated(RefrigRack(RackNum).CaseNum)) {
                        RefrigRack(RackNum).CaseNum.allocate(NumCases);
                    }
                    RefrigRack(RackNum).CaseNum(NumCases) = CaseNum;
                } else if (WalkInNum != 0) { // Name points to a walkin
                    NumWalkIns = 1;
                    RefrigRack(RackNum).NumWalkIns = 1;
                    if (!allocated(RefrigRack(RackNum).WalkInNum)) {
                        RefrigRack(RackNum).WalkInNum.allocate(NumWalkIns);
                    }
                    RefrigRack(RackNum).WalkInNum(NumWalkIns) = WalkInNum;
                } // NumNameMatches /= 1
            } // blank input for loads on rack

            if (NumCases > 0) {
                for (int caseIndex = 1; caseIndex <= NumCases; ++caseIndex) {
                    int caseID = RefrigRack(RackNum).CaseNum(caseIndex);
                    // mark all cases on rack as used by this system (checking for unused or non-unique cases)
                    ++RefrigCase(caseID).NumSysAttach;
                    // determine total capacity on rack
                    RefrigRack(RackNum).TotalRackLoad += RefrigCase(caseID).DesignRatedCap;
                } // CaseIndex=1,NumCases
                //     check that all refrigerated cases attached to a rack are to the same zone if heat rejection location is "Zone"
                //     however, won't matter if walk-in specified
                if (RefrigRack(RackNum).HeatRejectionLocation == HeatRejLocation::Zone && RefrigRack(RackNum).NumCases > 1 &&
                    RefrigCase(RefrigRack(RackNum).CaseNum(1)).ActualZoneNum != 0 && NumWalkIns < 1 && NumCoils < 1) {
                    int ZoneNum = RefrigCase(RefrigRack(RackNum).CaseNum(1)).ActualZoneNum;
                    for (int caseIndex = 2; caseIndex <= RefrigRack(RackNum).NumCases; ++caseIndex) {
                        if (RefrigCase(RefrigRack(RackNum).CaseNum(caseIndex)).ActualZoneNum == ZoneNum) {
                            continue;
                        }
                        ShowSevereError(state,
                                        format(R"({}{}="{}" : All cases attached to a rack must be in the same zone when {} equals "Zone".)",
                                               RoutineName,
                                               CurrentModuleObject,
                                               RefrigRack(RackNum).Name,
                                               cAlphaFieldNames(2)));
                        ErrorsFound = true;
                        break;
                    }
                } // heat rejection location is zone
            } // numcases > 0

            if (NumCoils > 0) {
                RefrigRack(RackNum).CoilFlag = true;
                for (int CoilIndex = 1; CoilIndex <= NumCoils; ++CoilIndex) {
                    int CoilNum = RefrigRack(RackNum).CoilNum(CoilIndex);
                    // mark all Coils on rack as used by this system (checking for unused or non-unique Coils)
                    ++WarehouseCoil(CoilNum).NumSysAttach;
                    // determine total capacity on rack
                    RefrigRack(RackNum).TotalRackLoad += WarehouseCoil(CoilNum).RatedSensibleCap;
                } // CoilIndex=1,NumCoils
            } // numcoils > 0

            if (NumWalkIns > 0) {
                for (int WalkInIndex = 1; WalkInIndex <= NumWalkIns; ++WalkInIndex) {
                    int WalkInID = RefrigRack(RackNum).WalkInNum(WalkInIndex);
                    // mark all WalkIns on rack as used by this system (checking for unused or non-unique WalkIns)
                    ++WalkIn(WalkInID).NumSysAttach;
                    // determine total capacity on rack
                    RefrigRack(RackNum).TotalRackLoad += WalkIn(WalkInID).DesignRatedCap;
                } // WalkInIndex=1,NumWalkIns
            } // NumWalkins

            if (NumWalkIns > 0 || NumCoils > 0) {
                // Get the heat rejection Zone node number from the zone name entered by the user (if heatrej location = zone)
                if (RefrigRack(RackNum).HeatRejectionLocation == HeatRejLocation::Zone) {
                    if (lAlphaBlanks(15)) {
                        ShowSevereError(
                            state,
                            format("{}{}=\"{}{} must be input if walkins or AirChillers connected to rack and heat rejection location = zone.",
                                   RoutineName,
                                   CurrentModuleObject,
                                   RefrigRack(RackNum).Name,
                                   cAlphaFieldNames(15)));
                        ErrorsFound = true;
                    } else { // alpha (15) not blank
                        RefrigRack(RackNum).HeatRejectionZoneNum = Util::FindItemInList(Alphas(15), state.dataHeatBal->Zone);
                        RefrigRack(RackNum).HeatRejectionZoneNodeNum =
                            DataZoneEquipment::GetSystemNodeNumberForZone(state, RefrigRack(RackNum).HeatRejectionZoneNum);
                        if (RefrigRack(RackNum).HeatRejectionZoneNum == 0) {
                            ShowSevereError(state,
                                            format("{}{}=\"{}\", invalid  {} not valid: {}",
                                                   RoutineName,
                                                   CurrentModuleObject,
                                                   RefrigRack(RackNum).Name,
                                                   cAlphaFieldNames(15),
                                                   Alphas(15)));
                            ErrorsFound = true;
                        } else {
                            state.dataRefrigCase->RefrigPresentInZone(RefrigRack(RackNum).HeatRejectionZoneNum) = true;
                        } // zonenum == 0
                    } // alpha 15 blank
                } // zone heat rej and walk-ins or coils present, must input heat rejection zone
            } // numwalkins or coils > 0

            // set condenser air flow and evap water pump power if autocalculated
            // autocalculate condenser evap water pump if needed
            if (RefrigRack(RackNum).CondenserType == DataHeatBalance::RefrigCondenserType::Evap &&
                RefrigRack(RackNum).EvapPumpPower == Constant::AutoCalculate) {
                RefrigRack(RackNum).EvapPumpPower = CondPumpRatePower * RefrigRack(RackNum).TotalRackLoad;
            }
            // autocalculate evap condenser air volume flow rate if needed
            if (RefrigRack(RackNum).CondenserType == DataHeatBalance::RefrigCondenserType::Evap &&
                RefrigRack(RackNum).CondenserAirFlowRate == Constant::AutoCalculate) {
                RefrigRack(RackNum).CondenserAirFlowRate = AirVolRateEvapCond * RefrigRack(RackNum).TotalRackLoad;
            }

        } // RackNum=1,NumRefrigeratedRacks

        state.dataRefrigCase->CheckEquipNameRackWaterCondenser.dimension(state.dataRefrigCase->NumRefrigeratedRacks, true);
    } //(NumRefrigeratedRacks > 0)

    if (state.dataRefrigCase->NumRefrigSystems > 0 || state.dataRefrigCase->NumTransRefrigSystems > 0) {

        if (state.dataRefrigCase->NumRefrigSystems > 0 && state.dataRefrigCase->NumRefrigCondensers == 0) {
            ShowSevereError(state,
                            "Refrigeration:System objects were found during input processing, however no Refrigeration condenser objects (which "
                            "may be either: ");
            ShowContinueError(state,
                              " Refrigeration:Condenser:AirCooled, Refrigeration:Condenser:WaterCooled, "
                              "Refrigeration:Condenser:EvaporativeCooled,or Refrigeration:Condenser:CascadeCooled) were found.");
            ErrorsFound = true;
        }
        if (state.dataRefrigCase->NumTransRefrigSystems > 0 && state.dataRefrigCase->NumSimulationGasCooler == 0) {
            ShowSevereError(state,
                            "Refrigeration:TranscriticalSystem objects were found during input processing, however no Refrigeration gas cooler "
                            "objects (Refrigeration:GasCooler:AirCooled) were found.");
            ErrorsFound = true;
        }
        if (state.dataRefrigCase->NumSimulationCompressors == 0) {
            ShowSevereError(
                state, "Refrigeration:System objects were found during input processing, however no Refrigeration:Compressor objects were found.");
            ErrorsFound = true;
        }

        //************ START CONDENSER INPUT  **************

        if (state.dataRefrigCase->NumSimulationCondAir > 0) {
            CurrentModuleObject = "Refrigeration:Condenser:AirCooled";
            for (int CondNum = 1; CondNum <= state.dataRefrigCase->NumSimulationCondAir; ++CondNum) {
                state.dataInputProcessing->inputProcessor->getObjectItem(state,
                                                                         CurrentModuleObject,
                                                                         CondNum,
                                                                         Alphas,
                                                                         NumAlphas,
                                                                         Numbers,
                                                                         NumNumbers,
                                                                         IOStatus,
                                                                         lNumericBlanks,
                                                                         lAlphaBlanks,
                                                                         cAlphaFieldNames,
                                                                         cNumericFieldNames);

                ErrorObjectHeader eoh{routineName, CurrentModuleObject, Alphas(1)};

                GlobalNames::VerifyUniqueInterObjectName(
                    state, state.dataRefrigCase->UniqueCondenserNames, Alphas(1), CurrentModuleObject, cAlphaFieldNames(1), ErrorsFound);
                Condenser(CondNum).Name = Alphas(1);
                state.dataHeatBal->HeatReclaimRefrigCondenser(CondNum).Name = Alphas(1);
                Condenser(CondNum).CapCurvePtr = Curve::GetCurveIndex(state, Alphas(2)); // convert curve name to number
                if (Condenser(CondNum).CapCurvePtr == 0) {
                    ShowSevereError(state,
                                    format("{}{}=\"{}\", invalid  {} not found:{}",
                                           RoutineName,
                                           CurrentModuleObject,
                                           Condenser(CondNum).Name,
                                           cAlphaFieldNames(2),
                                           Alphas(2)));
                    ErrorsFound = true;
                }

                // set start of count for number of systems attached to this condenser
                Condenser(CondNum).NumSysAttach = 0;
                if (!allocated(Condenser(CondNum).SysNum)) {
                    Condenser(CondNum).SysNum.allocate(state.dataRefrigCase->NumRefrigSystems);
                }

                // set CondenserType and rated temperature difference (51.7 - 35)C per ARI 460
                Condenser(CondNum).CondenserType = DataHeatBalance::RefrigCondenserType::Air;
                state.dataHeatBal->HeatReclaimRefrigCondenser(CondNum).SourceType = CurrentModuleObject;
                Condenser(CondNum).RatedDelT = CondARI460DelT; //= 16.7d0 ,Rated sat cond temp - dry bulb air T for air-cooled Condensers, ARI460
                Condenser(CondNum).RatedTCondense = CondARI460Tcond;
                if (Condenser(CondNum).CapCurvePtr > 0) {
                    Condenser(CondNum).RatedCapacity = Curve::CurveValue(state, Condenser(CondNum).CapCurvePtr, CondARI460DelT);
                }
                // elevation capacity correction on air-cooled condensers, Carrier correlation more conservative than Trane
                Condenser(CondNum).RatedCapacity *= (1.0 - 7.17e-5 * state.dataEnvrn->Elevation);
                if (Condenser(CondNum).RatedCapacity > 0.0) {
                    Curve::GetCurveMinMaxValues(state, Condenser(CondNum).CapCurvePtr, DelTempMin, DelTempMax);
                    Real64 Capmin = Curve::CurveValue(state, Condenser(CondNum).CapCurvePtr, DelTempMin) *
                                    (1.0 - 7.17e-5 * state.dataEnvrn->Elevation); // Mar 2011 bug fix
                    Real64 Capmax = Curve::CurveValue(state, Condenser(CondNum).CapCurvePtr, DelTempMax) *
                                    (1.0 - 7.17e-5 * state.dataEnvrn->Elevation); // Mar 2011 bug
                    Condenser(CondNum).TempSlope =
                        (DelTempMax - DelTempMin) / ((Capmax - Capmin)); // * ( 1.0 - 7.17e-5 * Elevation ) ) //Mar 2011 bug fix
                    Condenser(CondNum).MinCondLoad = Capmax - DelTempMax / Condenser(CondNum).TempSlope;
                } else {
                    ShowSevereError(state,
                                    format("{}{}=\"{}\" Condenser capacity curve per ARI 460 must be input and must be greater than 0 Watts at "
                                           "16.7C temperature difference.",
                                           RoutineName,
                                           CurrentModuleObject,
                                           Condenser(CondNum).Name));
                    ErrorsFound = true;
                }

                Condenser(CondNum).RatedSubcool = 0.0; // default value
                if (!lNumericBlanks(1)) {
                    Condenser(CondNum).RatedSubcool = Numbers(1);
                }

                // Get fan control type
                if (lAlphaBlanks(3)) {
                    Condenser(CondNum).FanSpeedControlType = FanSpeedCtrlType::ConstantSpeed; // default
                } else if ((Condenser(CondNum).FanSpeedControlType =
                                static_cast<FanSpeedCtrlType>(getEnumValue(fanSpeedCtrlTypeNamesUC, Alphas(3)))) == FanSpeedCtrlType::Invalid) {
                    ShowSevereInvalidKey(state, eoh, cAlphaFieldNames(3), Alphas(3));
                    ErrorsFound = true;
                } // Set fan control type

                if (!lNumericBlanks(2)) {
                    Condenser(CondNum).RatedFanPower = Numbers(2);
                }
                if ((lNumericBlanks(2)) || (Numbers(2) < 0.0)) {
                    ShowSevereError(state,
                                    format("{}{}=\"{}\" {} must be input greater than or equal to 0 Watts.",
                                           RoutineName,
                                           CurrentModuleObject,
                                           Condenser(CondNum).Name,
                                           cNumericFieldNames(2)));
                    ErrorsFound = true;
                }

                Condenser(CondNum).FanMinAirFlowRatio = 0.2; // default value
                if (!lNumericBlanks(3)) {
                    Condenser(CondNum).FanMinAirFlowRatio = Numbers(3);
                }

                // Check condenser air inlet node connection
                // Jan 2011 - added ability to reject heat to a zone from air-cooled condenser
                Condenser(CondNum).CondenserRejectHeatToZone = false;
                if (lAlphaBlanks(4)) {
                    Condenser(CondNum).InletAirNodeNum = 0;
                } else { // see if it's an outside air node name or an indoor zone name,
                    // have to check inside first because outside check automatically generates an error message
                    Condenser(CondNum).InletAirZoneNum = Util::FindItemInList(Alphas(4), state.dataHeatBal->Zone);
                    // need to clearly id node number for air inlet conditions and zone number for casecredit assignment
                    if (Condenser(CondNum).InletAirZoneNum != 0) {
                        // set condenser flag (later used to set system flag) and zone flag
                        Condenser(CondNum).InletAirNodeNum = DataZoneEquipment::GetSystemNodeNumberForZone(state, Condenser(CondNum).InletAirZoneNum);
                        Condenser(CondNum).CondenserRejectHeatToZone = true;
                        state.dataRefrigCase->RefrigPresentInZone(Condenser(CondNum).InletAirZoneNum) = true;
                    } else { // not in a conditioned zone, so see if it's outside
                        Condenser(CondNum).InletAirNodeNum =
                            NodeInputManager::GetOnlySingleNode(state,
                                                                Alphas(4),
                                                                ErrorsFound,
                                                                DataLoopNode::ConnectionObjectType::RefrigerationCondenserAirCooled,
                                                                Alphas(1),
                                                                DataLoopNode::NodeFluidType::Air,
                                                                DataLoopNode::ConnectionType::OutsideAirReference,
                                                                NodeInputManager::CompFluidStream::Primary,
                                                                DataLoopNode::ObjectIsParent);
                        if (!OutAirNodeManager::CheckOutAirNodeNumber(state, Condenser(CondNum).InletAirNodeNum)) {
                            // not outside and not a zone
                            ShowSevereError(state,
                                            format("{}{}=\"{}\", {} not found: {}",
                                                   RoutineName,
                                                   CurrentModuleObject,
                                                   Condenser(CondNum).Name,
                                                   cAlphaFieldNames(4),
                                                   Alphas(4)));
                            ShowContinueError(state, "...does not appear in an OutdoorAir:NodeList or as an OutdoorAir:Node or as a Zone.");
                            ErrorsFound = true;
                        } // checkoutairnodenumber
                    } // InletAirZoneNum \=0
                } // Condenser air inlet node connection

                Condenser(CondNum).EndUseSubcategory = "";
                if (!lAlphaBlanks(5)) {
                    Condenser(CondNum).EndUseSubcategory = Alphas(5);
                }

                Condenser(CondNum).RefOpCharge = 0.0;
                Condenser(CondNum).RefReceiverInventory = 0.0;
                Condenser(CondNum).RefPipingInventory = 0.0;
                if (!lNumericBlanks(4)) {
                    Condenser(CondNum).RefOpCharge = Numbers(4);
                }
                if (!lNumericBlanks(5)) {
                    Condenser(CondNum).RefReceiverInventory = Numbers(5);
                }
                if (!lNumericBlanks(6)) {
                    Condenser(CondNum).RefPipingInventory = Numbers(6);
                }

            } // Read input for REFRIGERATION:Condenser:AirCooled
        } // NumSimulationCondAir > 0

        if (state.dataRefrigCase->NumSimulationCondEvap > 0) {
            CurrentModuleObject = "Refrigeration:Condenser:EvaporativeCooled";
            for (int CondIndex = 1; CondIndex <= state.dataRefrigCase->NumSimulationCondEvap; ++CondIndex) {
                int CondNum = CondIndex + state.dataRefrigCase->NumSimulationCondAir;
                state.dataInputProcessing->inputProcessor->getObjectItem(state,
                                                                         CurrentModuleObject,
                                                                         CondIndex,
                                                                         Alphas,
                                                                         NumAlphas,
                                                                         Numbers,
                                                                         NumNumbers,
                                                                         IOStatus,
                                                                         lNumericBlanks,
                                                                         lAlphaBlanks,
                                                                         cAlphaFieldNames,
                                                                         cNumericFieldNames);

                ErrorObjectHeader eoh{routineName, CurrentModuleObject, Alphas(1)};

                GlobalNames::VerifyUniqueInterObjectName(
                    state, state.dataRefrigCase->UniqueCondenserNames, Alphas(1), CurrentModuleObject, cAlphaFieldNames(1), ErrorsFound);
                Condenser(CondNum).Name = Alphas(1);
                state.dataHeatBal->HeatReclaimRefrigCondenser(CondNum).Name = Alphas(1);

                // set start of count for number of systems attached to this condenser
                Condenser(CondNum).NumSysAttach = 0;
                if (!allocated(Condenser(CondNum).SysNum)) {
                    Condenser(CondNum).SysNum.allocate(state.dataRefrigCase->NumRefrigSystems);
                }

                // set CondenserType and rated Heat Rejection per ARI 490 rating
                Condenser(CondNum).CondenserType = DataHeatBalance::RefrigCondenserType::Evap;
                state.dataHeatBal->HeatReclaimRefrigCondenser(CondNum).SourceType = CurrentModuleObject;
                Condenser(CondNum).RatedTCondense = CondARI490Tcond;
                Condenser(CondNum).RatedDelT = CondARI490DelT;

                if ((!lNumericBlanks(1)) && (Numbers(1) > 0.0)) {
                    Condenser(CondNum).RatedCapacity = Numbers(1);
                } else {
                    ShowSevereError(state,
                                    format("{}{}=\"{}\" {} per ARI 490 must be input and must be greater than 0 Watts.",
                                           RoutineName,
                                           CurrentModuleObject,
                                           Condenser(CondNum).Name,
                                           cNumericFieldNames(1)));
                    ErrorsFound = true;
                }
                // Calculate capacity elevation derate factor per ARI 490 barometric pressure correction factor
                Condenser(CondNum).EvapElevFact = 1.0 - 3.074e-5 * state.dataEnvrn->Elevation;

                Condenser(CondNum).RatedSubcool = 0.0; // default value
                if ((!lNumericBlanks(2)) && (Numbers(2) > 0.0)) {
                    Condenser(CondNum).RatedSubcool = Numbers(2);
                }

                // Get fan control type
                if (lAlphaBlanks(2)) {
                    Condenser(CondNum).FanSpeedControlType = FanSpeedCtrlType::ConstantSpeed; // default
                } else if ((Condenser(CondNum).FanSpeedControlType =
                                static_cast<FanSpeedCtrlType>(getEnumValue(fanSpeedCtrlTypeNamesUC, Alphas(2)))) == FanSpeedCtrlType::Invalid) {
                    ShowSevereInvalidKey(state, eoh, cAlphaFieldNames(2), Alphas(2));
                    ErrorsFound = true;
                } // Set fan control type

                Condenser(CondNum).RatedFanPower = Numbers(3);
                if (Numbers(3) < 0.0) {
                    ShowSevereError(state,
                                    format("{}{}=\"{}\" {} must be greater than or equal to 0 Watts.",
                                           RoutineName,
                                           CurrentModuleObject,
                                           Condenser(CondNum).Name,
                                           cNumericFieldNames(3)));
                    ErrorsFound = true;
                }

                Condenser(CondNum).FanMinAirFlowRatio = 0.2; // default value
                if (!lNumericBlanks(4)) {
                    Condenser(CondNum).FanMinAirFlowRatio = Numbers(4);
                }

                // Enter min and max and default coefficients for evap condenser HRCF correlation
                // Defaults taken from 2008 BAC equipment for R22, R134a, series CXV
                // Correlation coefficients for other manufacturers are very similar per Hugh Henderson's work
                Condenser(CondNum).EvapCoeff1 = 6.63;
                Condenser(CondNum).EvapCoeff2 = 0.468;
                Condenser(CondNum).EvapCoeff3 = 17.93;
                Condenser(CondNum).EvapCoeff4 = -0.322;
                Condenser(CondNum).MinCapFacEvap = 0.5;
                Condenser(CondNum).MaxCapFacEvap = 5.0;
                NumNum = 5; // added warnings if below not blank but unused due to limits
                if (!lNumericBlanks(NumNum)) {
                    if (Numbers(NumNum) >= 0.0) {
                        Condenser(CondNum).EvapCoeff1 = Numbers(NumNum);
                    } else {
                        ShowWarningError(state,
                                         format("{}=\"{}\", {} is less than 0 and was not used. Default was used.",
                                                CurrentModuleObject,
                                                Condenser(CondNum).Name,
                                                cNumericFieldNames(NumNum)));
                    }
                }
                NumNum = 6; // EvapCoeff2 can't be equal to 0 because used in a denominator
                if (!lNumericBlanks(NumNum)) {
                    if (Numbers(NumNum) > 0.0) {
                        Condenser(CondNum).EvapCoeff2 = Numbers(NumNum);
                    } else {
                        ShowWarningError(state,
                                         format("{}=\"{}\", {} is less than or equal to 0 and was not used. Default was used.",
                                                CurrentModuleObject,
                                                Condenser(CondNum).Name,
                                                cNumericFieldNames(NumNum)));
                    }
                }
                NumNum = 7;
                if (!lNumericBlanks(NumNum)) {
                    if (Numbers(NumNum) >= 0.0) {
                        Condenser(CondNum).EvapCoeff3 = Numbers(NumNum);
                    } else {
                        ShowWarningError(state,
                                         format("{}=\"{}\", {} is less than 0 and was not used. Default was used.",
                                                CurrentModuleObject,
                                                Condenser(CondNum).Name,
                                                cNumericFieldNames(NumNum)));
                    }
                }
                NumNum = 8;
                if (!lNumericBlanks(NumNum)) {
                    if (Numbers(NumNum) >= -20.0) {
                        Condenser(CondNum).EvapCoeff4 = Numbers(NumNum);
                    } else {
                        ShowWarningError(state,
                                         format("{}=\"{}\", {} is less than -20 and was not used. Default was used.",
                                                CurrentModuleObject,
                                                Condenser(CondNum).Name,
                                                cNumericFieldNames(NumNum)));
                    }
                }
                NumNum = 9;
                if (!lNumericBlanks(NumNum)) {
                    if (Numbers(NumNum) >= 0.0) {
                        Condenser(CondNum).MinCapFacEvap = Numbers(NumNum);
                    } else {
                        ShowWarningError(state,
                                         format("{}=\"{}\", {} is less than 0 and was not used. Default was used.",
                                                CurrentModuleObject,
                                                Condenser(CondNum).Name,
                                                cNumericFieldNames(NumNum)));
                    }
                }
                NumNum = 10;
                if (!lNumericBlanks(NumNum)) {
                    if (Numbers(NumNum) >= 0.0) {
                        Condenser(CondNum).MaxCapFacEvap = Numbers(NumNum);
                    } else {
                        ShowWarningError(state,
                                         format("{}=\"{}\", {} is less than 0 and was not used. Default was used.",
                                                CurrentModuleObject,
                                                Condenser(CondNum).Name,
                                                cNumericFieldNames(NumNum)));
                    }
                }

                // Check condenser air inlet node connection
                if (lAlphaBlanks(3)) {
                    Condenser(CondNum).InletAirNodeNum = 0;
                } else {
                    Condenser(CondNum).InletAirNodeNum =
                        NodeInputManager::GetOnlySingleNode(state,
                                                            Alphas(3),
                                                            ErrorsFound,
                                                            DataLoopNode::ConnectionObjectType::RefrigerationCondenserEvaporativeCooled,
                                                            Alphas(1),
                                                            DataLoopNode::NodeFluidType::Air,
                                                            DataLoopNode::ConnectionType::OutsideAirReference,
                                                            NodeInputManager::CompFluidStream::Primary,
                                                            DataLoopNode::ObjectIsParent);
                    if (!OutAirNodeManager::CheckOutAirNodeNumber(state, Condenser(CondNum).InletAirNodeNum)) {
                        ShowSevereError(state,
                                        format("{}{}=\"{}\", {} not found: {}",
                                               RoutineName,
                                               CurrentModuleObject,
                                               Condenser(CondNum).Name,
                                               cAlphaFieldNames(3),
                                               Alphas(3)));
                        ShowContinueError(state, "...does not appear in an OutdoorAir:NodeList or as an OutdoorAir:Node.");
                        ErrorsFound = true;
                    }
                } // Condenser air inlet node connection

                NumNum = 11;
                Condenser(CondNum).RatedAirFlowRate = Numbers(NumNum);
                // Note the autocalculate feature for this value takes place in the system section because
                //  it is a function of the total cooling capacity of the cases served by the condenser

                // Evaporative condensers basin heater power as a function of temperature must be greater than or equal to 0
                NumNum = 12;
                Condenser(CondNum).BasinHeaterPowerFTempDiff = Numbers(NumNum);
                if (Numbers(NumNum) < 0.0) {
                    ShowSevereError(
                        state,
                        format(
                            "{}{}=\"{}\", {} must be >= 0", RoutineName, CurrentModuleObject, Condenser(CondNum).Name, cNumericFieldNames(NumNum)));
                    ErrorsFound = true;
                }

                NumNum = 13;
                Condenser(CondNum).BasinHeaterSetPointTemp = 2.0; // default
                if (!lNumericBlanks(NumNum)) {
                    Condenser(CondNum).BasinHeaterSetPointTemp = Numbers(NumNum);
                }
                if (Condenser(CondNum).BasinHeaterSetPointTemp < 2.0) {
                    ShowWarningError(state,
                                     format("{}=\"{}\", {} is less than 2 deg C. Freezing could occur.",
                                            CurrentModuleObject,
                                            Condenser(CondNum).Name,
                                            cNumericFieldNames(NumNum)));
                }

                NumNum = 14;
                Condenser(CondNum).EvapPumpPower = 1000.0; // default
                if (!lNumericBlanks(NumNum)) {
                    Condenser(CondNum).EvapPumpPower = Numbers(NumNum);
                }
                // Note the autocalculate feature for this value takes place in the system section because
                //  it is a function of the total cooling capacity of the cases served by the condenser

                // Get Evaporative Water System tank connections
                Condenser(CondNum).SupplyTankName = Alphas(4);
                if (lAlphaBlanks(4)) {
                    Condenser(CondNum).EvapWaterSupplyMode = WaterSupply::FromMains;
                } else {
                    Condenser(CondNum).EvapWaterSupplyMode = WaterSupply::FromTank;
                    WaterManager::SetupTankDemandComponent(state,
                                                           Condenser(CondNum).Name,
                                                           CurrentModuleObject,
                                                           Condenser(CondNum).SupplyTankName,
                                                           ErrorsFound,
                                                           Condenser(CondNum).EvapWaterSupTankID,
                                                           Condenser(CondNum).EvapWaterTankDemandARRID);
                }

                if (lAlphaBlanks(5)) {
                } else if ((Condenser(CondNum).evapAvailSched = Sched::GetSchedule(state, Alphas(5))) == nullptr) {
                    ShowSevereItemNotFound(state, eoh, cAlphaFieldNames(5), Alphas(5));
                    ErrorsFound = true;
                } else if (!Condenser(CondNum).evapAvailSched->checkMinVal(state, Clusive::In, 0.0)) {
                    Sched::ShowSevereBadMin(state, eoh, cAlphaFieldNames(5), Alphas(5), Clusive::In, 0.0);
                    ErrorsFound = true;
                }

                Condenser(CondNum).EndUseSubcategory = "";
                if (!lAlphaBlanks(6)) {
                    Condenser(CondNum).EndUseSubcategory = Alphas(6);
                }

                Condenser(CondNum).RefOpCharge = 0.0;
                Condenser(CondNum).RefReceiverInventory = 0.0;
                Condenser(CondNum).RefPipingInventory = 0.0;
                NumNum = 15;
                if (!lNumericBlanks(NumNum)) {
                    Condenser(CondNum).RefOpCharge = Numbers(NumNum);
                }
                NumNum = 16;
                if (!lNumericBlanks(NumNum)) {
                    Condenser(CondNum).RefReceiverInventory = Numbers(NumNum);
                }
                NumNum = 17;
                if (!lNumericBlanks(NumNum)) {
                    Condenser(CondNum).RefPipingInventory = Numbers(NumNum);
                }
            } // Read input for CONDENSER:REFRIGERATION:EVAPorativeCooled
        } // If NumSimulationCondEvap > 0

        if (state.dataRefrigCase->NumSimulationCondWater > 0) {
            CurrentModuleObject = "Refrigeration:Condenser:WaterCooled";
            for (int CondIndex = 1; CondIndex <= state.dataRefrigCase->NumSimulationCondWater; ++CondIndex) {
                int CondNum = CondIndex + state.dataRefrigCase->NumSimulationCondAir + state.dataRefrigCase->NumSimulationCondEvap;
                state.dataInputProcessing->inputProcessor->getObjectItem(state,
                                                                         CurrentModuleObject,
                                                                         CondIndex,
                                                                         Alphas,
                                                                         NumAlphas,
                                                                         Numbers,
                                                                         NumNumbers,
                                                                         IOStatus,
                                                                         lNumericBlanks,
                                                                         lAlphaBlanks,
                                                                         cAlphaFieldNames,
                                                                         cNumericFieldNames);

                ErrorObjectHeader eoh{routineName, CurrentModuleObject, Alphas(1)};

                GlobalNames::VerifyUniqueInterObjectName(
                    state, state.dataRefrigCase->UniqueCondenserNames, Alphas(1), CurrentModuleObject, cAlphaFieldNames(1), ErrorsFound);
                Condenser(CondNum).Name = Alphas(1);
                state.dataHeatBal->HeatReclaimRefrigCondenser(CondNum).Name = Alphas(1);

                // set start of count for number of systems attached to this condenser
                Condenser(CondNum).NumSysAttach = 0;
                if (!allocated(Condenser(CondNum).SysNum)) {
                    Condenser(CondNum).SysNum.allocate(state.dataRefrigCase->NumRefrigSystems);
                }

                // set CondenserType and rated Heat Rejection per ARI 450 rating
                Condenser(CondNum).CondenserType = DataHeatBalance::RefrigCondenserType::Water;
                state.dataHeatBal->HeatReclaimRefrigCondenser(CondNum).SourceType = CurrentModuleObject;
                if ((!lNumericBlanks(1)) && (Numbers(1) > 0.0)) {
                    Condenser(CondNum).RatedCapacity = Numbers(1);
                } else {
                    ShowSevereError(state,
                                    format("{}{}=\"{}\" {} per ARI 450 must be input and must be greater than 0 Watts.",
                                           RoutineName,
                                           CurrentModuleObject,
                                           Condenser(CondNum).Name,
                                           cNumericFieldNames(1)));
                    ErrorsFound = true;
                }

                if ((!lNumericBlanks(2)) && (Numbers(2) > 0.0)) {
                    Condenser(CondNum).RatedTCondense = Numbers(2);
                } else {
                    ShowSevereError(state,
                                    format("{}{}=\"{}\" {} per ARI 450 must be input and must be greater than 0 C.",
                                           RoutineName,
                                           CurrentModuleObject,
                                           Condenser(CondNum).Name,
                                           cNumericFieldNames(2)));
                    ErrorsFound = true;
                }

                if (!lNumericBlanks(3)) {
                    if (Numbers(3) >= 0.0) {
                        Condenser(CondNum).RatedSubcool = Numbers(3);
                    } else {
                        ShowSevereError(state,
                                        format("{}{}=\"{}\" {} must be greater than or equal to zero.",
                                               RoutineName,
                                               CurrentModuleObject,
                                               Condenser(CondNum).Name,
                                               cNumericFieldNames(3)));
                        ErrorsFound = true;
                    }
                } else {
                    Condenser(CondNum).RatedSubcool = 0.0; // default value
                }

                if ((!lNumericBlanks(4)) && (Numbers(4) > 0.0)) {
                    Condenser(CondNum).RatedWaterInletT = Numbers(4);
                    Condenser(CondNum).RatedApproachT = Condenser(CondNum).RatedTCondense - Numbers(4);
                } else {
                    ShowSevereError(state,
                                    format("{}{}=\"{}\" {} must be input and greater than zero.",
                                           RoutineName,
                                           CurrentModuleObject,
                                           Condenser(CondNum).Name,
                                           cNumericFieldNames(4)));
                    ErrorsFound = true;
                }

                Condenser(CondNum).InletNode =
                    NodeInputManager::GetOnlySingleNode(state,
                                                        Alphas(2),
                                                        ErrorsFound,
                                                        DataLoopNode::ConnectionObjectType::RefrigerationCondenserWaterCooled,
                                                        Alphas(1),
                                                        DataLoopNode::NodeFluidType::Water,
                                                        DataLoopNode::ConnectionType::Inlet,
                                                        NodeInputManager::CompFluidStream::Primary,
                                                        DataLoopNode::ObjectIsNotParent);
                Condenser(CondNum).OutletNode =
                    NodeInputManager::GetOnlySingleNode(state,
                                                        Alphas(3),
                                                        ErrorsFound,
                                                        DataLoopNode::ConnectionObjectType::RefrigerationCondenserWaterCooled,
                                                        Alphas(1),
                                                        DataLoopNode::NodeFluidType::Water,
                                                        DataLoopNode::ConnectionType::Outlet,
                                                        NodeInputManager::CompFluidStream::Primary,
                                                        DataLoopNode::ObjectIsNotParent);
                // Check node connections
                BranchNodeConnections::TestCompSet(state, CurrentModuleObject, Alphas(1), Alphas(2), Alphas(3), "Water Cooled Condenser Nodes");
                // Get loop flow type
                if ((Condenser(CondNum).FlowType = static_cast<CndsrFlowType>(getEnumValue(cndsrFlowTypeNamesUC, Alphas(4)))) ==
                    CndsrFlowType::Invalid) {

                    ShowSevereInvalidKey(state, eoh, cAlphaFieldNames(4), Alphas(4));
                    ErrorsFound = true;
                } // Set FlowType

                // Get outlet temperature schedule for variable flow case
                if (Condenser(CondNum).FlowType == CndsrFlowType::Variable) {
                    if (lAlphaBlanks(5)) {
                    } else if ((Condenser(CondNum).outletTempSched = Sched::GetSchedule(state, Alphas(5))) == nullptr) {
                        ShowSevereItemNotFound(state, eoh, cAlphaFieldNames(5), Alphas(5));
                        ErrorsFound = true;
                    }
                } // Outlet temperature schedule

                // Get volumetric flow rate if applicable
                else if (Condenser(CondNum).FlowType == CndsrFlowType::Constant) {
                    if ((!lNumericBlanks(5)) && (Numbers(5) > 0.0)) {
                        Condenser(CondNum).DesVolFlowRate = Numbers(5);
                        Condenser(CondNum).VolFlowRate = Numbers(5);
                    } else {
                        ShowSevereError(state,
                                        format("{}{}=\"{}\" {} must be greater than zero.",
                                               RoutineName,
                                               CurrentModuleObject,
                                               Condenser(CondNum).Name,
                                               cNumericFieldNames(5)));
                        ShowContinueError(state, "Revise flow rates.");
                        ErrorsFound = true;
                    }
                    PlantUtilities::RegisterPlantCompDesignFlow(state, Condenser(CondNum).InletNode, Condenser(CondNum).DesVolFlowRate);
                }

                // Get maximum flow rates
                if (Numbers(6) > 0.0) {
                    Condenser(CondNum).VolFlowRateMax = Numbers(6);
                    // Check constant flow for max violation, if applicable
                    if (Condenser(CondNum).FlowType == CndsrFlowType::Constant && Condenser(CondNum).VolFlowRate > Numbers(6)) {
                        ShowSevereError(state,
                                        format("{}{}=\"{}\" {} > {} .",
                                               RoutineName,
                                               CurrentModuleObject,
                                               Condenser(CondNum).Name,
                                               cNumericFieldNames(5),
                                               cNumericFieldNames(6)));
                        ShowContinueError(state, "Revise flow rates.");
                        ErrorsFound = true;
                    } // Error check on max flow rate
                } else {
                    ShowSevereError(state,
                                    format("{}{}=\"{}\" {} must be greater than zero.",
                                           RoutineName,
                                           CurrentModuleObject,
                                           Condenser(CondNum).Name,
                                           cNumericFieldNames(6)));
                    ErrorsFound = true;
                }

                // Get max/min allowed water temps
                Condenser(CondNum).OutletTempMax = Numbers(7);
                Condenser(CondNum).InletTempMin = Numbers(8);

                Condenser(CondNum).EndUseSubcategory = "";
                if (!lAlphaBlanks(6)) {
                    Condenser(CondNum).EndUseSubcategory = Alphas(6);
                }

                Condenser(CondNum).RefOpCharge = 0.0;
                Condenser(CondNum).RefReceiverInventory = 0.0;
                Condenser(CondNum).RefPipingInventory = 0.0;
                if (!lNumericBlanks(9)) {
                    Condenser(CondNum).RefOpCharge = Numbers(9);
                }
                if (!lNumericBlanks(10)) {
                    Condenser(CondNum).RefReceiverInventory = Numbers(10);
                }
                if (!lNumericBlanks(11)) {
                    Condenser(CondNum).RefPipingInventory = Numbers(11);
                }

            } // Read input for CONDENSER:REFRIGERATION:WaterCooled

            state.dataRefrigCase->CheckEquipNameWaterCondenser.dimension(state.dataRefrigCase->NumRefrigCondensers, true);
        } // NumSimulationCondWater > 0

        // cascade condensers assumed to provide zero subcooling
        if (state.dataRefrigCase->NumSimulationCascadeCondensers > 0) {
            CurrentModuleObject = "Refrigeration:Condenser:Cascade";
            for (int CondIndex = 1; CondIndex <= state.dataRefrigCase->NumSimulationCascadeCondensers; ++CondIndex) {
                int CondNum = CondIndex + state.dataRefrigCase->NumSimulationCondAir + state.dataRefrigCase->NumSimulationCondEvap +
                              state.dataRefrigCase->NumSimulationCondWater;
                state.dataInputProcessing->inputProcessor->getObjectItem(state,
                                                                         CurrentModuleObject,
                                                                         CondIndex,
                                                                         Alphas,
                                                                         NumAlphas,
                                                                         Numbers,
                                                                         NumNumbers,
                                                                         IOStatus,
                                                                         lNumericBlanks,
                                                                         lAlphaBlanks,
                                                                         cAlphaFieldNames,
                                                                         cNumericFieldNames);

                ErrorObjectHeader eoh{routineName, CurrentModuleObject, Alphas(1)};

                GlobalNames::VerifyUniqueInterObjectName(
                    state, state.dataRefrigCase->UniqueCondenserNames, Alphas(1), CurrentModuleObject, cAlphaFieldNames(1), ErrorsFound);
                Condenser(CondNum).Name = Alphas(1);
                state.dataHeatBal->HeatReclaimRefrigCondenser(CondNum).Name = Alphas(1);

                // set start of count for number of systems attached to this condenser
                Condenser(CondNum).NumSysAttach = 0;
                if (!allocated(Condenser(CondNum).SysNum)) {
                    Condenser(CondNum).SysNum.allocate(state.dataRefrigCase->NumRefrigSystems);
                }

                // set CondenserType
                Condenser(CondNum).CondenserType = DataHeatBalance::RefrigCondenserType::Cascade;

                if (!lNumericBlanks(1)) {
                    Condenser(CondNum).RatedTCondense = Numbers(1);
                } else {
                    ShowSevereError(
                        state,
                        format("{}{}=\"{}\" {} must be input.", RoutineName, CurrentModuleObject, Condenser(CondNum).Name, cNumericFieldNames(1)));
                    ErrorsFound = true;
                }

                if (!lNumericBlanks(2)) {
                    if (Numbers(2) >= 0.0) {
                        Condenser(CondNum).RatedApproachT = Numbers(2);
                    } else {
                        ShowSevereError(state,
                                        format("{}{}=\"{}\" {} must be greater than or equal to zero.",
                                               RoutineName,
                                               CurrentModuleObject,
                                               Condenser(CondNum).Name,
                                               cNumericFieldNames(2)));
                        ErrorsFound = true;
                    }
                } else {
                    Condenser(CondNum).RatedApproachT = DefaultCascadeCondApproach;
                }

                if ((!lNumericBlanks(3)) && (Numbers(3) > 0.0)) {
                    Condenser(CondNum).RatedCapacity = Numbers(3);
                } else {
                    ShowSevereError(state,
                                    format("{}{}=\"{}\" {} must be in put and must be greater than or equal to zero.",
                                           RoutineName,
                                           CurrentModuleObject,
                                           Condenser(CondNum).Name,
                                           cNumericFieldNames(3)));
                    ErrorsFound = true;
                }

                // Get condensing temperature type, either fixed by design or allowed to float to match other loads on supply system
                if (lAlphaBlanks(2)) {
                    Condenser(CondNum).CascadeTempControl = CascadeCndsrTempCtrlType::TempSet;
                } else if ((Condenser(CondNum).CascadeTempControl = static_cast<CascadeCndsrTempCtrlType>(
                                getEnumValue(cascaseCndsrTempCtrlTypeNamesUC, Alphas(2)))) == CascadeCndsrTempCtrlType::Invalid) {
                    ShowSevereInvalidKey(state, eoh, cAlphaFieldNames(2), Alphas(2));
                    ErrorsFound = true;
                } // string comparison to key choices

                Condenser(CondNum).CascadeRatedEvapTemp = Condenser(CondNum).RatedTCondense - Condenser(CondNum).RatedApproachT;

                // future - add refrigerant inventory on system side accepting reject heat (as was done for secondary)
                Condenser(CondNum).RefOpCharge = 0.0;
                Condenser(CondNum).RefReceiverInventory = 0.0;
                Condenser(CondNum).RefPipingInventory = 0.0;
                if (!lNumericBlanks(4)) {
                    Condenser(CondNum).RefOpCharge = Numbers(4);
                }
                if (!lNumericBlanks(5)) {
                    Condenser(CondNum).RefReceiverInventory = Numbers(5);
                }
                if (!lNumericBlanks(6)) {
                    Condenser(CondNum).RefPipingInventory = Numbers(6);
                }

            } // Read input for CONDENSER:REFRIGERATION:Cascade
        } // NumSimulationCascadeCondensers > 0

        //************ END CONDENSER INPUT   **************

        //**********  START GAS COOLER INPUT  **********

        if (state.dataRefrigCase->NumSimulationGasCooler > 0) {
            CurrentModuleObject = "Refrigeration:GasCooler:AirCooled";
            for (int GCNum = 1; GCNum <= state.dataRefrigCase->NumSimulationGasCooler; ++GCNum) {
                state.dataInputProcessing->inputProcessor->getObjectItem(state,
                                                                         CurrentModuleObject,
                                                                         GCNum,
                                                                         Alphas,
                                                                         NumAlphas,
                                                                         Numbers,
                                                                         NumNumbers,
                                                                         IOStatus,
                                                                         lNumericBlanks,
                                                                         lAlphaBlanks,
                                                                         cAlphaFieldNames,
                                                                         cNumericFieldNames);
                ErrorObjectHeader eoh{routineName, CurrentModuleObject, Alphas(1)};

                GasCooler(GCNum).Name = Alphas(1);

                GasCooler(GCNum).CapCurvePtr = Curve::GetCurveIndex(state, Alphas(2)); // convert curve name to number
                if (GasCooler(GCNum).CapCurvePtr == 0) {
                    ShowSevereItemNotFound(state, eoh, cAlphaFieldNames(2), Alphas(2));
                    ErrorsFound = true;
                }

                // set start of count for number of systems attached to this gas cooler
                GasCooler(GCNum).NumSysAttach = 0;
                if (!allocated(GasCooler(GCNum).SysNum)) {
                    GasCooler(GCNum).SysNum.allocate(state.dataRefrigCase->NumTransRefrigSystems);
                }

                GasCooler(GCNum).RatedApproachT = 3.0; // rated CO2 gas cooler approach temperature
                if (GasCooler(GCNum).CapCurvePtr > 0) {
                    GasCooler(GCNum).RatedCapacity = Curve::CurveValue(state, GasCooler(GCNum).CapCurvePtr, GasCooler(GCNum).RatedApproachT);
                }
                // elevation capacity correction on air-cooled condensers, Carrier correlation more conservative than Trane
                GasCooler(GCNum).RatedCapacity *= (1.0 - 7.17e-5 * state.dataEnvrn->Elevation);
                if (GasCooler(GCNum).RatedCapacity > 0.0) {
                    Curve::GetCurveMinMaxValues(state, GasCooler(GCNum).CapCurvePtr, DelTempMin, DelTempMax);
                    Real64 Capmin = Curve::CurveValue(state, GasCooler(GCNum).CapCurvePtr, DelTempMin) * (1.0 - 7.17e-5 * state.dataEnvrn->Elevation);
                    Real64 Capmax = Curve::CurveValue(state, GasCooler(GCNum).CapCurvePtr, DelTempMax) * (1.0 - 7.17e-5 * state.dataEnvrn->Elevation);
                    GasCooler(GCNum).TempSlope = (DelTempMax - DelTempMin) / ((Capmax - Capmin));
                    GasCooler(GCNum).MinCondLoad = Capmax - DelTempMax / GasCooler(GCNum).TempSlope;
                } else {
                    ShowSevereError(
                        state,
                        format("{}{}=\"{}\" Gas Cooler capacity curve must be input and must be greater than 0 Watts at 3C temperature difference.",
                               RoutineName,
                               CurrentModuleObject,
                               GasCooler(GCNum).Name));
                    ErrorsFound = true;
                }

                // Get fan control type
                if (lAlphaBlanks(3)) {
                    GasCooler(GCNum).FanSpeedControlType = FanSpeedCtrlType::ConstantSpeed; // default
                } else if ((GasCooler(GCNum).FanSpeedControlType = static_cast<FanSpeedCtrlType>(getEnumValue(fanSpeedCtrlTypeNamesUC, Alphas(3)))) ==
                           FanSpeedCtrlType::Invalid) {
                    ShowSevereInvalidKey(state, eoh, cAlphaFieldNames(3), Alphas(3));
                    ErrorsFound = true;
                }

                // Gas cooler fan power
                GasCooler(GCNum).RatedFanPower = 5000.0; // default value
                if (!lNumericBlanks(1)) {
                    GasCooler(GCNum).RatedFanPower = Numbers(1);
                }
                if (Numbers(1) < 0.0) {
                    ShowSevereError(state,
                                    format("{}{}=\"{}\" {} must be input greater than or equal to 0 Watts.",
                                           RoutineName,
                                           CurrentModuleObject,
                                           GasCooler(GCNum).Name,
                                           cNumericFieldNames(1)));
                    ErrorsFound = true;
                }

                // Gas cooler minimum fan air flow ratio
                GasCooler(GCNum).FanMinAirFlowRatio = 0.2; // default value
                if (!lNumericBlanks(2)) {
                    GasCooler(GCNum).FanMinAirFlowRatio = Numbers(2);
                }
                if ((GasCooler(GCNum).FanMinAirFlowRatio < 0.0) || (GasCooler(GCNum).FanMinAirFlowRatio > 1.0)) {
                    ShowSevereError(state,
                                    format("{}{}=\"{}\" {} must be a value between zero and one.  The default value (0.2) will be used.",
                                           RoutineName,
                                           CurrentModuleObject,
                                           GasCooler(GCNum).Name,
                                           cNumericFieldNames(2)));
                    GasCooler(GCNum).FanMinAirFlowRatio = 0.2;
                }

                // Gas cooler transition temperature
                GasCooler(GCNum).TransitionTemperature = 2.7e1; // default value
                if (!lNumericBlanks(3)) {
                    GasCooler(GCNum).TransitionTemperature = Numbers(3);
                }
                if (GasCooler(GCNum).TransitionTemperature < 2.5e1) {
                    ShowWarningError(state,
                                     format("{}{}=\"{}\" {} is low (less than 25C).  Consider raising the transition temperature to operate for "
                                            "longer periods of time in the subcritical region.",
                                            RoutineName,
                                            CurrentModuleObject,
                                            GasCooler(GCNum).Name,
                                            cNumericFieldNames(3)));
                }
                if (GasCooler(GCNum).TransitionTemperature > 30.978) {
                    ShowWarningError(
                        state,
                        format("{}{}=\"{}\" {} is greater than the critical temperature of carbon dioxide.  The default value (27C) will be used.",
                               RoutineName,
                               CurrentModuleObject,
                               GasCooler(GCNum).Name,
                               cNumericFieldNames(3)));
                    GasCooler(GCNum).TransitionTemperature = 2.7e1;
                }

                // Gas cooler approach temperature for transcritical operation
                GasCooler(GCNum).GasCoolerApproachT = 3.0; // default value
                if (!lNumericBlanks(4)) {
                    GasCooler(GCNum).GasCoolerApproachT = Numbers(4);
                }
                if (GasCooler(GCNum).GasCoolerApproachT < 0.0) {
                    ShowSevereError(state,
                                    format("{}{}=\"{}\" {} must be greater than 0C.",
                                           RoutineName,
                                           CurrentModuleObject,
                                           GasCooler(GCNum).Name,
                                           cNumericFieldNames(4)));
                    ErrorsFound = true;
                }

                // Gas cooler temperature difference for subcritical operation
                GasCooler(GCNum).SubcriticalTempDiff = 1.0e1; // default value
                if (!lNumericBlanks(5)) {
                    GasCooler(GCNum).SubcriticalTempDiff = Numbers(5);
                }
                if (GasCooler(GCNum).SubcriticalTempDiff < 0.0) {
                    ShowSevereError(state,
                                    format("{}{}=\"{}\" {} must be greater than 0C.",
                                           RoutineName,
                                           CurrentModuleObject,
                                           GasCooler(GCNum).Name,
                                           cNumericFieldNames(5)));
                    ErrorsFound = true;
                }

                // Gas cooler minimum condensing temperature for subcritical operation
                GasCooler(GCNum).MinCondTemp = 1.0e1; // default value
                if (!lNumericBlanks(6)) {
                    GasCooler(GCNum).MinCondTemp = Numbers(6);
                }
                if (GasCooler(GCNum).MinCondTemp > 30.9) {
                    ShowSevereError(state,
                                    format("{}{}=\"{}\" {} must be less than the critical temperature of carbon dioxide (31C).",
                                           RoutineName,
                                           CurrentModuleObject,
                                           GasCooler(GCNum).Name,
                                           cNumericFieldNames(6)));
                    ErrorsFound = true;
                }

                // Check GasCooler air inlet node connection
                GasCooler(GCNum).GasCoolerRejectHeatToZone = false;
                if (lAlphaBlanks(4)) {
                    GasCooler(GCNum).InletAirNodeNum = 0;
                } else { // see if it's an outside air node name or an indoor zone name,
                    // have to check inside first because outside check automatically generates an error message
                    GasCooler(GCNum).InletAirZoneNum = Util::FindItemInList(Alphas(4), state.dataHeatBal->Zone);
                    // need to clearly id node number for air inlet conditions and zone number for casecredit assignment
                    if (GasCooler(GCNum).InletAirZoneNum != 0) {
                        // set condenser flag (later used to set system flag) and zone flag
                        GasCooler(GCNum).InletAirNodeNum = DataZoneEquipment::GetSystemNodeNumberForZone(state, GasCooler(GCNum).InletAirZoneNum);
                        GasCooler(GCNum).GasCoolerRejectHeatToZone = true;
                        state.dataRefrigCase->RefrigPresentInZone(GasCooler(GCNum).InletAirZoneNum) = true;
                    } else { // not in a conditioned zone, so see if it's outside
                        GasCooler(GCNum).InletAirNodeNum =
                            NodeInputManager::GetOnlySingleNode(state,
                                                                Alphas(4),
                                                                ErrorsFound,
                                                                DataLoopNode::ConnectionObjectType::RefrigerationGasCoolerAirCooled,
                                                                Alphas(1),
                                                                DataLoopNode::NodeFluidType::Air,
                                                                DataLoopNode::ConnectionType::OutsideAirReference,
                                                                NodeInputManager::CompFluidStream::Primary,
                                                                DataLoopNode::ObjectIsParent);
                        if (!OutAirNodeManager::CheckOutAirNodeNumber(state, GasCooler(GCNum).InletAirNodeNum)) {
                            // not outside and not a zone
                            ShowSevereItemNotFound(state, eoh, cAlphaFieldNames(4), Alphas(4));
                            ShowContinueError(state, "...does not appear in an OutdoorAir:NodeList or as an OutdoorAir:Node or as a Zone.");
                            ErrorsFound = true;
                        } // checkoutairnodenumber
                    } // InletAirZoneNum \=0
                } // Gas cooler air inlet node connection

                GasCooler(GCNum).EndUseSubcategory = "";
                if (!lAlphaBlanks(5)) {
                    GasCooler(GCNum).EndUseSubcategory = Alphas(5);
                }

                GasCooler(GCNum).RefOpCharge = 0.0;
                GasCooler(GCNum).RefReceiverInventory = 0.0;
                GasCooler(GCNum).RefPipingInventory = 0.0;
                if (!lNumericBlanks(7)) {
                    GasCooler(GCNum).RefOpCharge = Numbers(7);
                }
                if (!lNumericBlanks(8)) {
                    GasCooler(GCNum).RefReceiverInventory = Numbers(8);
                }
                if (!lNumericBlanks(9)) {
                    GasCooler(GCNum).RefPipingInventory = Numbers(9);
                }

            } // Read input for REFRIGERATION:GasCooler:AirCooled
        } // NumSimulationGasCooler > 0

        //**********  END GAS COOLER INPUT  **********

        //************ START SECONDARY LOOP INPUT (before system input) **************
        if (state.dataRefrigCase->NumSimulationSecondarySystems > 0) {
            CurrentModuleObject = "Refrigeration:SecondarySystem";
            for (int SecondaryNum = 1; SecondaryNum <= state.dataRefrigCase->NumSimulationSecondarySystems; ++SecondaryNum) {
                state.dataInputProcessing->inputProcessor->getObjectItem(state,
                                                                         CurrentModuleObject,
                                                                         SecondaryNum,
                                                                         Alphas,
                                                                         NumAlphas,
                                                                         Numbers,
                                                                         NumNumbers,
                                                                         IOStatus,
                                                                         lNumericBlanks,
                                                                         lAlphaBlanks,
                                                                         cAlphaFieldNames,
                                                                         cNumericFieldNames);

                ErrorObjectHeader eoh{routineName, CurrentModuleObject, Alphas(1)};
                Util::IsNameEmpty(state, Alphas(1), CurrentModuleObject, ErrorsFound);

                Secondary(SecondaryNum).Name = Alphas(1);

                //   Find the loads on the secondary loop: can be input in form of case or walkin or CaseAndWalkInList names
                Real64 NominalTotalCaseCap = 0.0;
                NumCases = 0;
                Real64 NominalTotalCoilCap = 0.0;
                int NumCoils = 0;
                NumWalkIns = 0;
                Real64 NominalTotalWalkInCap = 0.0;
                Secondary(SecondaryNum).RefInventory = 0.0;

                //   Read display case and walkin assignments for this secondary
                AlphaNum = 2;
                if (lAlphaBlanks(AlphaNum)) {
                    // No cases or walkins specified, ie, secondary has no load
                    ShowSevereError(state,
                                    format("{}{}=\"{}\", has no loads, must have at least one of: {}",
                                           RoutineName,
                                           CurrentModuleObject,
                                           Secondary(SecondaryNum).Name,
                                           cAlphaFieldNames(AlphaNum)));
                    ErrorsFound = true;
                } else { // (.NOT. lAlphaBlanks(AlphaNum))

                    // Entry for Alphas(AlphaNum) can be either a Case, WalkIn Coil, or CaseAndWalkInList name
                    int CaseAndWalkInListNum = 0;
                    int CaseNum = 0;
                    int WalkInNum = 0;
                    int CoilNum = 0;
                    if (state.dataRefrigCase->NumSimulationCaseAndWalkInLists > 0) {
                        CaseAndWalkInListNum = Util::FindItemInList(Alphas(AlphaNum), CaseAndWalkInList);
                    }
                    if (state.dataRefrigCase->NumSimulationCases > 0) {
                        CaseNum = Util::FindItemInList(Alphas(AlphaNum), RefrigCase);
                    }
                    if (state.dataRefrigCase->NumSimulationWalkIns > 0) {
                        WalkInNum = Util::FindItemInList(Alphas(AlphaNum), WalkIn);
                    }
                    if (state.dataRefrigCase->NumSimulationRefrigAirChillers > 0) {
                        CoilNum = Util::FindItemInList(Alphas(AlphaNum), WarehouseCoil);
                    }
                    int NumNameMatches = 0;
                    if (CaseAndWalkInListNum != 0) {
                        ++NumNameMatches;
                    }
                    if (CaseNum != 0) {
                        ++NumNameMatches;
                    }
                    if (WalkInNum != 0) {
                        ++NumNameMatches;
                    }
                    if (CoilNum != 0) {
                        ++NumNameMatches;
                    }

                    if (NumNameMatches != 1) { // name must uniquely point to a list or a single case or walkin or coil
                        ErrorsFound = true;
                        if (NumNameMatches == 0) {
                            ShowSevereError(state,
                                            format("{}{}=\"{}\", has an invalid {}: {}",
                                                   RoutineName,
                                                   CurrentModuleObject,
                                                   Secondary(SecondaryNum).Name,
                                                   cAlphaFieldNames(AlphaNum),
                                                   Alphas(AlphaNum)));
                        } else if (NumNameMatches > 1) {
                            ShowSevereError(state,
                                            format("{}{}=\"{}\", has a non-unique name that could be either a {}: {}",
                                                   RoutineName,
                                                   CurrentModuleObject,
                                                   Secondary(SecondaryNum).Name,
                                                   cAlphaFieldNames(AlphaNum),
                                                   Alphas(AlphaNum)));
                        } // num matches = 0 or > 1
                    } else if (CaseAndWalkInListNum != 0) { // Name points to a CaseAndWalkInList
                        NumCoils = CaseAndWalkInList(CaseAndWalkInListNum).NumCoils;
                        NumCases = CaseAndWalkInList(CaseAndWalkInListNum).NumCases;
                        NumWalkIns = CaseAndWalkInList(CaseAndWalkInListNum).NumWalkIns;
                        Secondary(SecondaryNum).NumCases = NumCases;
                        Secondary(SecondaryNum).NumCoils = NumCoils;
                        Secondary(SecondaryNum).NumWalkIns = NumWalkIns;
                        if (!allocated(Secondary(SecondaryNum).CaseNum)) {
                            Secondary(SecondaryNum).CaseNum.allocate(NumCases);
                        }
                        Secondary(SecondaryNum).CaseNum({1, NumCases}) = CaseAndWalkInList(CaseAndWalkInListNum).CaseItemNum({1, NumCases});
                        if (!allocated(Secondary(SecondaryNum).CoilNum)) {
                            Secondary(SecondaryNum).CoilNum.allocate(NumCoils);
                        }
                        Secondary(SecondaryNum).CoilNum({1, NumCoils}) = CaseAndWalkInList(CaseAndWalkInListNum).CoilItemNum({1, NumCoils});
                        if (!allocated(Secondary(SecondaryNum).WalkInNum)) {
                            Secondary(SecondaryNum).WalkInNum.allocate(NumWalkIns);
                        }
                        Secondary(SecondaryNum).WalkInNum({1, NumWalkIns}) = CaseAndWalkInList(CaseAndWalkInListNum).WalkInItemNum({1, NumWalkIns});
                    } else if (CaseNum != 0) { // Name points to a case
                        NumCases = 1;
                        Secondary(SecondaryNum).NumCases = 1;
                        if (!allocated(Secondary(SecondaryNum).CaseNum)) {
                            Secondary(SecondaryNum).CaseNum.allocate(NumCases);
                        }
                        Secondary(SecondaryNum).CaseNum(NumCases) = CaseNum;
                    } else if (CoilNum != 0) { // Name points to a coil
                        NumCoils = 1;
                        Secondary(SecondaryNum).NumCoils = 1;
                        if (!allocated(Secondary(SecondaryNum).CoilNum)) {
                            Secondary(SecondaryNum).CoilNum.allocate(NumCoils);
                        }
                        Secondary(SecondaryNum).CoilNum(NumCoils) = CoilNum;
                    } else if (WalkInNum != 0) { // Name points to a walkin
                        NumWalkIns = 1;
                        Secondary(SecondaryNum).NumWalkIns = 1;
                        if (!allocated(Secondary(SecondaryNum).WalkInNum)) {
                            Secondary(SecondaryNum).WalkInNum.allocate(NumWalkIns);
                        }
                        Secondary(SecondaryNum).WalkInNum(NumWalkIns) = WalkInNum;
                    } // NumNameMatches /= 1
                } // blank input for loads on secondary

                if (NumCases > 0) {
                    // Find lowest design T loop fluid out of secondary chiller
                    // Sum rated capacity of all cases on Secondary
                    for (int caseIndex = 1; caseIndex <= NumCases; ++caseIndex) {
                        // mark all cases on Secondary as used by this Secondary - checking for unused or non-unique cases
                        int CaseNum = Secondary(SecondaryNum).CaseNum(caseIndex);
                        ++RefrigCase(CaseNum).NumSysAttach;
                        NominalTotalCaseCap += RefrigCase(CaseNum).DesignRatedCap * RefrigCase(CaseNum).RatedRTF;
                        Secondary(SecondaryNum).RefInventory += RefrigCase(CaseNum).DesignRefrigInventory;
                        if (caseIndex == 1) { // look for lowest case design evap T for Secondary
                            Secondary(SecondaryNum).TMinNeeded = RefrigCase(CaseNum).EvapTempDesign;
                        } else {
                            Secondary(SecondaryNum).TMinNeeded = min(RefrigCase(CaseNum).EvapTempDesign, Secondary(SecondaryNum).TMinNeeded);
                        }
                    } // CaseIndex=1,NumCases
                } // Numcases > 0

                if (NumCoils > 0) {
                    // Find lowest design T loop fluid out of secondary chiller
                    // Sum rated capacity of all Coils on Secondary
                    for (int CoilIndex = 1; CoilIndex <= NumCoils; ++CoilIndex) {
                        // mark all Coils on Secondary as used by this Secondary - checking for unused or non-unique Coils
                        int CoilNum = Secondary(SecondaryNum).CoilNum(CoilIndex);
                        ++WarehouseCoil(CoilNum).NumSysAttach;
                        NominalTotalCoilCap += WarehouseCoil(CoilNum).RatedSensibleCap;
                        Secondary(SecondaryNum).RefInventory += WarehouseCoil(CoilNum).DesignRefrigInventory;
                        if ((CoilIndex == 1) && (NumCases == 0)) { // look for lowest Coil design evap T for Secondary
                            Secondary(SecondaryNum).TMinNeeded = WarehouseCoil(CoilNum).TEvapDesign;
                        } else {
                            Secondary(SecondaryNum).TMinNeeded = min(WarehouseCoil(CoilNum).TEvapDesign, Secondary(SecondaryNum).TMinNeeded);
                        }
                    } // CoilIndex=1,NumCoils
                } // NumCoils > 0

                if (NumWalkIns > 0) {
                    // Find lowest design T loop fluid out of secondary chiller
                    // Sum rated capacity of all WalkIns on Secondary
                    for (int WalkInIndex = 1; WalkInIndex <= NumWalkIns; ++WalkInIndex) {
                        // mark all WalkIns on Secondary as used by this Secondary - checking for unused or non-unique WalkIns
                        int WalkInID = Secondary(SecondaryNum).WalkInNum(WalkInIndex);
                        ++WalkIn(WalkInID).NumSysAttach;
                        NominalTotalWalkInCap += WalkIn(WalkInID).DesignRatedCap;
                        Secondary(SecondaryNum).RefInventory += WalkIn(WalkInID).DesignRefrigInventory;
                        if ((WalkInIndex == 1) && (NumCases == 0) && (NumCoils == 0)) { // look for lowest load design evap T for Secondary
                            Secondary(SecondaryNum).TMinNeeded = WalkIn(WalkInID).TEvapDesign;
                        } else {
                            Secondary(SecondaryNum).TMinNeeded = min(Secondary(SecondaryNum).TMinNeeded, WalkIn(WalkInID).TEvapDesign);
                        }
                    } // WalkInIndex=1,NumWalkIns
                } // Numwalkins > 0

                // Get circulating fluid type
                AlphaNum = 3;
                if (lAlphaBlanks(AlphaNum)) {
                    ShowSevereEmptyField(state, eoh, cAlphaFieldNames(AlphaNum));
                    ErrorsFound = true;
                } else if ((Secondary(SecondaryNum).FluidType = static_cast<SecFluidType>(getEnumValue(secFluidTypeNamesUC, Alphas(AlphaNum)))) ==
                           SecFluidType::Invalid) {
                    ShowSevereInvalidKey(state, eoh, cAlphaFieldNames(AlphaNum), Alphas(AlphaNum));
                    ErrorsFound = true;
                } // Set FluidType

                AlphaNum = 4;
                Secondary(SecondaryNum).FluidName = Alphas(AlphaNum);
                if (Secondary(SecondaryNum).FluidName.empty()) {
                    ShowSevereEmptyField(state, eoh, cAlphaFieldNames(AlphaNum));
                    ErrorsFound = true;
                } else if ((Secondary(SecondaryNum).glycol = Fluid::GetGlycol(state, Secondary(SecondaryNum).FluidName)) != nullptr) {
                } else if ((Secondary(SecondaryNum).refrig = Fluid::GetRefrig(state, Secondary(SecondaryNum).FluidName)) != nullptr) {
                } else {
                    ShowSevereItemNotFound(state, eoh, cAlphaFieldNames(AlphaNum), Alphas(AlphaNum));
                    ErrorsFound = true;
                }

                // Error messages for refrigerants and glycols already found in fluidproperties

                // Note remainder of inputs for secondary don't follow IDD input order because of different interpretations
                //   and intermediate calculations used to assign default values for brine type vs. liquid overfeed/phase change loops

                if (!lNumericBlanks(3)) {
                    Secondary(SecondaryNum).TEvapDesign = Numbers(3);
                } else {
                    ShowSevereError(state,
                                    format("{}{}=\"{}\" {} must be specified.",
                                           RoutineName,
                                           CurrentModuleObject,
                                           Secondary(SecondaryNum).Name,
                                           cNumericFieldNames(3)));
                    ErrorsFound = true;
                } // blank on N3

                if (!lNumericBlanks(4)) {
                    Secondary(SecondaryNum).TApproachDifRated = Numbers(4);
                } else {
                    ShowSevereError(state,
                                    format("{}{}=\"{}\" {} must be specified.",
                                           RoutineName,
                                           CurrentModuleObject,
                                           Secondary(SecondaryNum).Name,
                                           cNumericFieldNames(4)));
                    ErrorsFound = true;
                } // blank on N4

                //^^^^^^^Now look at input and once-only calculations required only for liquid/brine secondary loops^^^^^^^^^^^^^^^^^^^^^^
                //   Ensure that required input data is not missing prior to performing the following once-only calculations
                if (ErrorsFound) {
                    ShowFatalError(state,
                                   format("{}{}=\"{}\", Program terminated due to previous condition(s).",
                                          RoutineName,
                                          CurrentModuleObject,
                                          Secondary(SecondaryNum).Name));
                } // ErrorsFound

                Real64 CpBrineRated = 0.0;
                Real64 PumpTotRatedFlowVol(0.0);   // Rated flow from input pump data, m3/s
                Real64 SecondaryFlowVolRated(0.0); // Rated flow of secondary fluid, used to calculate capacity (m3/s)
                Real64 TBrineOutRated(0.0);        // Rated temperature of circ fluid LEAVING heat exchanger,C
                Real64 TBrineInRated(0.0);         // Rated temperature of circ fluid going INTO heat exchanger, C

                if (Secondary(SecondaryNum).FluidType == SecFluidType::AlwaysLiquid) {
                    if (!lNumericBlanks(5)) {
                        Secondary(SecondaryNum).TRangeDifRated = Numbers(5);
                    } else {
                        ShowSevereError(state,
                                        format("{}{}=\"{}\", {} must be specified.",
                                               RoutineName,
                                               CurrentModuleObject,
                                               Secondary(SecondaryNum).Name,
                                               cNumericFieldNames(5)));
                        ShowContinueError(state, format("...when {}=\"FluidAlwaysLiquid\".", cAlphaFieldNames(3)));
                        ErrorsFound = true;
                    } // blank on N5

                    // Get fluid properties at rated conditions, will be used to calculate ht exchgr effectiveness
                    TBrineOutRated = Secondary(SecondaryNum).TEvapDesign + Secondary(SecondaryNum).TApproachDifRated;
                    TBrineInRated = TBrineOutRated + Secondary(SecondaryNum).TRangeDifRated;
                    Real64 TBrineAverage = (TBrineOutRated + TBrineInRated) / 2.0;
                    Secondary(SecondaryNum).TBrineAverage = TBrineAverage;
                    DensityBrineRated = Secondary(SecondaryNum).glycol->getDensity(state, TBrineAverage, TrackMessage);
                    Secondary(SecondaryNum).DensityBrineRated = DensityBrineRated;
                    CpBrineRated = Secondary(SecondaryNum).glycol->getSpecificHeat(state, TBrineAverage, TrackMessage);
                    Secondary(SecondaryNum).CpBrineRated = CpBrineRated;

                    // Users can input either design brine flow (m3/s), or capacity in W, or both.  Now have
                    //  temperatures needed to calculate either the loop cooling capacity or fluid flow rate, if one was not input
                    //  Don't need to save as a flow vol as a permanent var because calc whichever is missing here
                    Real64 FlowMassRated(0.0); // Design mass flow rate of circ fluid in secondary loop(kg/s)
                    if ((!lNumericBlanks(1)) && (!lNumericBlanks(2))) {
                        // Both values input, check for approximate agreement
                        Secondary(SecondaryNum).CoolingLoadRated = Numbers(1);
                        SecondaryFlowVolRated = Numbers(2);
                        FlowMassRated = SecondaryFlowVolRated * DensityBrineRated;
                        Real64 NominalSecondaryCapacity = FlowMassRated * CpBrineRated * Secondary(SecondaryNum).TRangeDifRated;
                        Real64 TestDelta = (NominalSecondaryCapacity - Secondary(SecondaryNum).CoolingLoadRated) / NominalSecondaryCapacity;
                        if (std::abs(TestDelta) > 0.2) {
                            ShowWarningError(state,
                                             format("{}=\"{} You may wish to check the system definition. Based upon the design flow rate and "
                                                    "range temperature difference,  The nominal secondary loop heat exchanger capacity is, "
                                                    "{:.0R} but the specified design capacity is,  {:.0R}",
                                                    CurrentModuleObject,
                                                    Secondary(SecondaryNum).Name,
                                                    NominalSecondaryCapacity,
                                                    Secondary(SecondaryNum).CoolingLoadRated));
                        }
                    } else if (!lNumericBlanks(1)) {
                        Secondary(SecondaryNum).CoolingLoadRated = Numbers(1);
                        // Calc flow vol rated
                        FlowMassRated = Secondary(SecondaryNum).CoolingLoadRated / (CpBrineRated * Secondary(SecondaryNum).TRangeDifRated);
                        SecondaryFlowVolRated = FlowMassRated / DensityBrineRated;
                    } else if (!lNumericBlanks(2)) {
                        SecondaryFlowVolRated = Numbers(2);
                        // Calc rated load
                        FlowMassRated = SecondaryFlowVolRated * DensityBrineRated;
                        Secondary(SecondaryNum).CoolingLoadRated = FlowMassRated * CpBrineRated * Secondary(SecondaryNum).TRangeDifRated;
                    } else {
                        ShowSevereError(state,
                                        format(R"({}{}="{}", Either "{}" OR "{}" must be input.)",
                                               RoutineName,
                                               CurrentModuleObject,
                                               Secondary(SecondaryNum).Name,
                                               cNumericFieldNames(1),
                                               cNumericFieldNames(2)));
                        ErrorsFound = true;
                    } // Capacity Input via either or both options

                    if (!ErrorsFound) {
                        // Calculate heat exchanger effectiveness based on rated flow and temperature differences
                        Secondary(SecondaryNum).HeatExchangeEta =
                            Secondary(SecondaryNum).CoolingLoadRated /
                            (FlowMassRated * CpBrineRated * (TBrineInRated - Secondary(SecondaryNum).TEvapDesign));
                        Secondary(SecondaryNum).TBrineInRated = TBrineInRated;
                        if (Secondary(SecondaryNum).HeatExchangeEta > 0.99) {
                            ShowWarningError(
                                state,
                                format("{}=\"{} You may wish to check the system definition.  The heat exchanger effectiveness is, {:.2R}",
                                       CurrentModuleObject,
                                       Secondary(SecondaryNum).Name,
                                       Secondary(SecondaryNum).HeatExchangeEta));
                            Secondary(SecondaryNum).HeatExchangeEta = 0.99;
                        }
                    } else {
                        ShowContinueError(state, "...remainder of this object input skipped due to previous errors");
                        continue;
                    }

                    PumpTotRatedFlowVol = SecondaryFlowVolRated;
                    if (!lNumericBlanks(7)) {
                        PumpTotRatedFlowVol = Numbers(7);
                    }

                } else { // FluidType = FluidTypePhaseChange     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                    if (!lNumericBlanks(1)) {
                        Secondary(SecondaryNum).CoolingLoadRated = Numbers(1);
                    } else {
                        Secondary(SecondaryNum).CoolingLoadRated = NominalTotalCaseCap + NominalTotalWalkInCap;
                        // first estimate, will later be adjusted to include pump power
                    } // input capacity

                    Secondary(SecondaryNum).TCondense = Secondary(SecondaryNum).TEvapDesign + Secondary(SecondaryNum).TApproachDifRated;
                    Secondary(SecondaryNum).CircRate = DefaultCircRate;
                    if (!lNumericBlanks(10)) {
                        Secondary(SecondaryNum).CircRate = Numbers(10);
                    }

                    DensityPhaseChange =
                        Secondary(SecondaryNum).refrig->getSatDensity(state, Secondary(SecondaryNum).TCondense, 0.0, TrackMessageAlt);
                    DeltaHPhaseChange =
                        Secondary(SecondaryNum).refrig->getSatEnthalpy(state, Secondary(SecondaryNum).TCondense, 1.0, TrackMessageAlt) -
                        Secondary(SecondaryNum).refrig->getSatEnthalpy(state, Secondary(SecondaryNum).TCondense, 0.0, TrackMessageAlt);

                    // TotRatedFlowVol= capacity*circrate/deltahphasechange/density
                    Real64 CalcTotFlowVol =
                        Secondary(SecondaryNum).CoolingLoadRated * Secondary(SecondaryNum).CircRate / (DensityPhaseChange * DeltaHPhaseChange);
                    PumpTotRatedFlowVol = CalcTotFlowVol;
                    if (!lNumericBlanks(7)) {
                        PumpTotRatedFlowVol = Numbers(7);
                        Real64 CalcCircRate = DensityPhaseChange * DeltaHPhaseChange * PumpTotRatedFlowVol / Secondary(SecondaryNum).CoolingLoadRated;
                        Real64 DiffCircRates = (CalcCircRate - Secondary(SecondaryNum).CircRate) / Secondary(SecondaryNum).CircRate;
                        if (std::abs(DiffCircRates) > 0.3) {
                            ShowWarningError(state,
                                             format("{}=\"{} {} Produces a circulating rate of {:.2R} ;  A circulating rate of {:.2R} would need "
                                                    "a {} of {:.2R} m3/s",
                                                    CurrentModuleObject,
                                                    Secondary(SecondaryNum).Name,
                                                    cNumericFieldNames(7),
                                                    CalcCircRate,
                                                    Secondary(SecondaryNum).CircRate,
                                                    cNumericFieldNames(7),
                                                    CalcTotFlowVol));
                        } // warning check on pump flow rate vs circ rate input
                    } // blank pump flow rate
                    SecondaryFlowVolRated = PumpTotRatedFlowVol;

                } // fluid type AlwaysLiquid or PhaseChange ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

                // Read number of pumps (or pump stages) in secondary loop
                int NumPumps = 1; // default value
                if ((!lNumericBlanks(6)) && (Numbers(6) >= 1)) {
                    NumPumps = Numbers(6);
                }
                Secondary(SecondaryNum).NumPumps = NumPumps;
                // Get pump power (users can input either power in W or head in Pa or both)
                // Assume pump impeller efficiency is 0.78 (consistent with E+ Pump auto-sizing assumption)
                // Assume pump motor efficiency is 0.85 (Goulds Pumps motor data sheet)
                // It is important that tot rated head must be for specific fluid
                Real64 PumpTotRatedHead(0.0); // Total pump rated head on secondary loop (Pa)

                if ((!lNumericBlanks(8)) && (!lNumericBlanks(9))) {
                    Secondary(SecondaryNum).PumpTotRatedPower = Numbers(8);
                    PumpTotRatedHead = Numbers(9);
                    Real64 ErrSecondPumpPower = (Secondary(SecondaryNum).PumpTotRatedPower -
                                                 PumpTotRatedFlowVol * PumpTotRatedHead / (PumpImpellerEfficiency * PumpMotorEfficiency)) /
                                                Secondary(SecondaryNum).PumpTotRatedPower;
                    if (std::abs(ErrSecondPumpPower) > 0.35) {
                        ShowWarningError(
                            state,
                            format("{}=\"{} Input value for {} not consistent with input value for {}. {} will be used",
                                   CurrentModuleObject,
                                   Secondary(SecondaryNum).Name,
                                   cNumericFieldNames(9),
                                   cNumericFieldNames(8),
                                   cNumericFieldNames(8))); // generous diff allowed because comparing to my assumed impeller and motor effs
                    }
                } else if (!lNumericBlanks(8)) {
                    Secondary(SecondaryNum).PumpTotRatedPower = Numbers(8);
                } else if (!lNumericBlanks(9)) {
                    PumpTotRatedHead = Numbers(9);
                    Secondary(SecondaryNum).PumpTotRatedPower =
                        PumpTotRatedFlowVol * PumpTotRatedHead / (PumpImpellerEfficiency * PumpMotorEfficiency);
                } else {
                    ShowSevereError(state,
                                    format(R"({}{}="{}", Either "{}" OR "{}" must be input.)",
                                           RoutineName,
                                           CurrentModuleObject,
                                           Secondary(SecondaryNum).Name,
                                           cNumericFieldNames(8),
                                           cNumericFieldNames(9)));
                    ErrorsFound = true;
                } // Either or pump power Input variations (head or power)

                // Get pump drive type
                AlphaNum = 5;
                if (lAlphaBlanks(AlphaNum)) {
                    Secondary(SecondaryNum).PumpControlType = SecPumpCtrl::Constant; // default
                } else if ((Secondary(SecondaryNum).PumpControlType = static_cast<SecPumpCtrl>(getEnumValue(secPumpCtrlNamesUC, Alphas(AlphaNum)))) ==
                           SecPumpCtrl::Invalid) {
                    ShowSevereInvalidKey(state, eoh, cAlphaFieldNames(AlphaNum), Alphas(AlphaNum));
                    ErrorsFound = true;
                }

                //  Print warning if Pump Control = Constant and Variable Speed Curve is specified.
                if ((Secondary(SecondaryNum).PumpControlType == SecPumpCtrl::Constant) && (!lAlphaBlanks(AlphaNum + 1))) {
                    ShowWarningError(state,
                                     format(R"({}{}="{}", A {} is specified even though {} is "CONSTANT".)",
                                            RoutineName,
                                            CurrentModuleObject,
                                            Secondary(SecondaryNum).Name,
                                            cAlphaFieldNames(AlphaNum + 1),
                                            cAlphaFieldNames(AlphaNum)));
                    ShowContinueError(state,
                                      format("The secondary loop pump(s) will be modeled as constant speed and the {} will be ignored.",
                                             cAlphaFieldNames(AlphaNum + 1)));
                }

                if (Secondary(SecondaryNum).PumpControlType == SecPumpCtrl::Constant) {
                    // Set incremental flow and power amounts for pump dispatch
                    Secondary(SecondaryNum).PumpIncrementFlowVol = PumpTotRatedFlowVol / NumPumps;
                    Secondary(SecondaryNum).PumpIncrementPower = Secondary(SecondaryNum).PumpTotRatedPower / NumPumps;
                } else { // Variable speed drive need to read in power curve
                    AlphaNum = 6;
                    Secondary(SecondaryNum).VarSpeedCurvePtr = Curve::GetCurveIndex(state, Alphas(AlphaNum)); // convert curve name to number
                    if (Secondary(SecondaryNum).VarSpeedCurvePtr == 0) {
                        ShowSevereItemNotFound(state, eoh, cAlphaFieldNames(AlphaNum), Alphas(AlphaNum));
                        ErrorsFound = true;
                    }
                    ErrorsFound |= Curve::CheckCurveDims(state,
                                                         Secondary(SecondaryNum).VarSpeedCurvePtr, // Curve index
                                                         {1},                                      // Valid dimensions
                                                         RoutineName,                              // Routine name
                                                         CurrentModuleObject,                      // Object Type
                                                         Secondary(SecondaryNum).Name,             // Object Name
                                                         cAlphaFieldNames(AlphaNum));              // Field Name
                } // input power conditions/levels for constant or variable speed pump drives

                // Default non-hermetic motor eff at 85% and all shaft power goes to heat in fluid
                // In a semi-hermetic motor, assume all power to motor goes to heat in fluid
                Secondary(SecondaryNum).PumpPowerToHeat = PumpMotorEfficiency;
                NumNum = 11;
                if (!lNumericBlanks(NumNum)) {
                    if ((0.5 <= Numbers(NumNum)) && (1.0 >= Numbers(NumNum))) {
                        Secondary(SecondaryNum).PumpPowerToHeat = Numbers(NumNum);
                    } else {
                        ShowWarningError(state,
                                         format("{}{}=\"{}\" {} must be between 0.5 and 1.0. Default value of : {:.3R} will be used",
                                                RoutineName,
                                                CurrentModuleObject,
                                                Secondary(SecondaryNum).Name,
                                                cNumericFieldNames(NumNum),
                                                PumpMotorEfficiency));
                    } // range of pump moter heat to fluid
                } // blank input for pumppowertoheat

                // Distribution piping heat gain - optional
                //  Input UA and Zone containing the bulk of the secondary coolant distribution piping
                //  This Zone ID will be used to determine the temperature used for distribution piping heat gain.
                //  Zone Id is only required if Sum UA Distribution Piping >0.0
                //  Get the Zone node number from the zone name entered by the user
                Secondary(SecondaryNum).SumUADistPiping = 0.0;
                AlphaNum = 7;
                NumNum = 12;
                if (!lNumericBlanks(NumNum) && !lAlphaBlanks(AlphaNum)) {
                    Secondary(SecondaryNum).SumUADistPiping = Numbers(NumNum);
                    Secondary(SecondaryNum).DistPipeZoneNum = Util::FindItemInList(Alphas(AlphaNum), state.dataHeatBal->Zone);
                    Secondary(SecondaryNum).DistPipeZoneNodeNum =
                        DataZoneEquipment::GetSystemNodeNumberForZone(state, Secondary(SecondaryNum).DistPipeZoneNum);

                    if (Secondary(SecondaryNum).DistPipeZoneNum == 0) {
                        ShowSevereError(state,
                                        format("{}{}=\"{}\", invalid  {} not valid: {}",
                                               RoutineName,
                                               CurrentModuleObject,
                                               Secondary(SecondaryNum).Name,
                                               cAlphaFieldNames(AlphaNum),
                                               Alphas(AlphaNum)));
                        ErrorsFound = true;
                    } else {
                        state.dataRefrigCase->RefrigPresentInZone(Secondary(SecondaryNum).DistPipeZoneNum) = true;
                    }

                    if (Secondary(SecondaryNum).DistPipeZoneNodeNum == 0) {
                        ShowSevereError(
                            state,
                            format("{}{}=\"{}\" System Node Number not found for {} = {} even though {} is greater than zero. Distribution "
                                   "piping heat gain cannot be calculated unless a controlled Zone (appear in a ZoneHVAC:EquipmentConnections "
                                   "object.) is defined to determine the environmental temperature surrounding the piping.",
                                   RoutineName,
                                   CurrentModuleObject,
                                   Secondary(SecondaryNum).Name,
                                   cAlphaFieldNames(AlphaNum),
                                   Alphas(AlphaNum),
                                   cNumericFieldNames(NumNum)));
                        ErrorsFound = true;
                    }
                } else if (!lNumericBlanks(NumNum) && lAlphaBlanks(AlphaNum)) {
                    ShowWarningError(
                        state,
                        format("{}{}=\"{}\", {} not found even though {} is greater than zero. Distribution piping heat gain will not be "
                               "calculated unless a Zone is defined to determine the environmental temperature surrounding the piping.",
                               RoutineName,
                               CurrentModuleObject,
                               Secondary(SecondaryNum).Name,
                               cAlphaFieldNames(AlphaNum),
                               cNumericFieldNames(NumNum)));
                } else if (lNumericBlanks(NumNum) && !lAlphaBlanks(AlphaNum)) {
                    ShowWarningError(
                        state,
                        format("{}{}=\"{}\", {} will not be used and distribution piping heat gain will not be calculated because {} was blank.",
                               RoutineName,
                               CurrentModuleObject,
                               Secondary(SecondaryNum).Name,
                               cAlphaFieldNames(AlphaNum),
                               cNumericFieldNames(NumNum)));
                } // distribution piping

                // Separator/receiver heat gain - optional
                //  Input UA and Zone containing the Separator/receiver
                //  This Zone ID will be used to determine the temperature used for Separator/receiver heat gain.
                //  Zone Id is only required if Sum UA Separator/receiver >0.0
                //  Get the Zone node number from the zone name entered by the user
                Secondary(SecondaryNum).SumUAReceiver = 0.0;
                AlphaNum = 8;
                NumNum = 13;
                if (!lNumericBlanks(NumNum) && !lAlphaBlanks(AlphaNum)) {
                    Secondary(SecondaryNum).SumUAReceiver = Numbers(NumNum);
                    Secondary(SecondaryNum).ReceiverZoneNum = Util::FindItemInList(Alphas(AlphaNum), state.dataHeatBal->Zone);
                    Secondary(SecondaryNum).ReceiverZoneNodeNum =
                        DataZoneEquipment::GetSystemNodeNumberForZone(state, Secondary(SecondaryNum).ReceiverZoneNum);

                    if (Secondary(SecondaryNum).ReceiverZoneNum == 0) {
                        ShowSevereError(state,
                                        format("{}{}=\"{}\", invalid  {} not valid: {}",
                                               RoutineName,
                                               CurrentModuleObject,
                                               Secondary(SecondaryNum).Name,
                                               cAlphaFieldNames(AlphaNum),
                                               Alphas(AlphaNum)));
                        ErrorsFound = true;
                    } else {
                        state.dataRefrigCase->RefrigPresentInZone(Secondary(SecondaryNum).ReceiverZoneNum) = true;
                    }
                    if (Secondary(SecondaryNum).ReceiverZoneNodeNum == 0) {
                        ShowSevereError(
                            state,
                            format("{}{}=\"{}\" System Node Number not found for {} = {} even though {} is greater than zero. Receiver heat gain "
                                   "cannot be calculated unless a controlled Zone (appear in a ZoneHVAC:EquipmentConnections object.) is defined "
                                   "to determine the environmental temperature surrounding the Receiver.",
                                   RoutineName,
                                   CurrentModuleObject,
                                   Secondary(SecondaryNum).Name,
                                   cAlphaFieldNames(AlphaNum),
                                   Alphas(AlphaNum),
                                   cNumericFieldNames(NumNum)));
                        ErrorsFound = true;
                    }
                } else if (!lNumericBlanks(NumNum) && lAlphaBlanks(AlphaNum)) {
                    ShowWarningError(
                        state,
                        format("{}{}=\"{}\", {} not found even though {} is greater than zero. Receiver heat gain will not be calculated unless "
                               "a Zone is defined to determine the environmental temperature surrounding the Receiver.",
                               RoutineName,
                               CurrentModuleObject,
                               Secondary(SecondaryNum).Name,
                               cAlphaFieldNames(AlphaNum),
                               cNumericFieldNames(NumNum)));
                } else if (lNumericBlanks(NumNum) && !lAlphaBlanks(AlphaNum)) {
                    ShowWarningError(state,
                                     format("{}{}=\"{}\", {} will not be used and Receiver heat gain will not be calculated because {} was blank.",
                                            RoutineName,
                                            CurrentModuleObject,
                                            Secondary(SecondaryNum).Name,
                                            cAlphaFieldNames(AlphaNum),
                                            cNumericFieldNames(NumNum)));
                } // Receiver

                NumNum = 14;
                Secondary(SecondaryNum).ChillerRefInventory = 0.0;
                if (!lNumericBlanks(NumNum)) {
                    Secondary(SecondaryNum).ChillerRefInventory = Numbers(NumNum);
                }
                if (Secondary(SecondaryNum).ChillerRefInventory < 0.0) {
                    Secondary(SecondaryNum).ChillerRefInventory = 0.0;
                    ShowWarningError(state,
                                     format("{}{}=\"{}\", The value specified for {} is less than zero. The default value of zero will be used.",
                                            RoutineName,
                                            CurrentModuleObject,
                                            Secondary(SecondaryNum).Name,
                                            cNumericFieldNames(NumNum)));
                }

                AlphaNum = 9;
                if (!lAlphaBlanks(AlphaNum)) {
                    Secondary(SecondaryNum).EndUseSubcategory = Alphas(AlphaNum);
                }

                // Error checks on secondary loop:
                // Note, rated capacities can be far off from operating capacities, but rough checks here
                //       (don't include dist piping or receiver heat gains).
                // Load limit logic here (maxvolflow and maxload used in calcs later)
                Secondary(SecondaryNum).MaxVolFlow = min(SecondaryFlowVolRated, PumpTotRatedFlowVol);
                Real64 NominalSecondaryRefLoad = NominalTotalCaseCap + NominalTotalWalkInCap + Secondary(SecondaryNum).PumpTotRatedPower;

                if (Secondary(SecondaryNum).FluidType == SecFluidType::AlwaysLiquid) {
                    if (TBrineOutRated > (Secondary(SecondaryNum).TMinNeeded + 0.5)) {
                        ShowWarningError(state,
                                         format("{}=\"{} The design brine temperature to the refrigeration loads: {:.1R} ;",
                                                CurrentModuleObject,
                                                Secondary(SecondaryNum).Name,
                                                TBrineOutRated));
                        ShowContinueError(state,
                                          format(" is greater than the design inlet temperature for at least one of the cases or walkins: {:.1R}",
                                                 Secondary(SecondaryNum).TMinNeeded));
                        ShowContinueError(
                            state, " Compare your Approach and Evaporating Temperature to the design inlet temperatures needed for the loads.");
                        // ErrorsFound = .TRUE.
                    } // Tbrine out warning
                    Real64 CapacityAtMaxVolFlow = Secondary(SecondaryNum).MaxVolFlow * Secondary(SecondaryNum).HeatExchangeEta *
                                                  (CpBrineRated * DensityBrineRated) * (TBrineInRated - Secondary(SecondaryNum).TEvapDesign);
                    Secondary(SecondaryNum).MaxLoad = min(Secondary(SecondaryNum).CoolingLoadRated, CapacityAtMaxVolFlow);
                    Real64 DeltaCap1 =
                        std::abs((Secondary(SecondaryNum).CoolingLoadRated - CapacityAtMaxVolFlow) / Secondary(SecondaryNum).CoolingLoadRated);
                    if (DeltaCap1 > (0.3)) { // diff between chiller rating and capacity at max flow > 30%
                        ShowWarningError(state,
                                         format("{}=\"{}\" You may wish to check the system sizing.  The nominal secondary loop heat exchanger "
                                                "capacity is {:.0R} But the capacity based upon the maximum flow rate is {:.0R}",
                                                CurrentModuleObject,
                                                Secondary(SecondaryNum).Name,
                                                Secondary(SecondaryNum).CoolingLoadRated,
                                                CapacityAtMaxVolFlow));
                    } // DeltaCap1 > .3
                } else {                         // Fluid type phase change                !^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                    if (lNumericBlanks(1)) {     // Chiller/evaporator capacity was not specified
                        if (lNumericBlanks(7)) { // Pump power was not input, calc based on flow and head
                            // need to refine because capacity calculated, but needs to include pump power (which was prev
                            //   estimated based upon capacity which had been estimated as sum of case and walk-in capacities)
                            PumpTotRatedFlowVol =
                                NominalSecondaryRefLoad * Secondary(SecondaryNum).CircRate / (DensityPhaseChange * DeltaHPhaseChange);
                            Secondary(SecondaryNum).PumpTotRatedPower =
                                PumpTotRatedFlowVol * PumpTotRatedHead / (PumpImpellerEfficiency * PumpMotorEfficiency);
                            // need to recalc nominal load with new pump power value
                            NominalSecondaryRefLoad = NominalTotalCaseCap + NominalTotalWalkInCap + Secondary(SecondaryNum).PumpTotRatedPower;
                            if (Secondary(SecondaryNum).PumpControlType == SecPumpCtrl::Constant) {
                                // Set incremental flow and power amounts for pump dispatch
                                Secondary(SecondaryNum).PumpIncrementFlowVol = PumpTotRatedFlowVol / NumPumps;
                                Secondary(SecondaryNum).PumpIncrementPower = Secondary(SecondaryNum).PumpTotRatedPower / NumPumps;
                            } // constant speed pump
                        } // Pump power was not specified
                        Secondary(SecondaryNum).CoolingLoadRated = NominalSecondaryRefLoad;
                    } // Chiller/evap capacity was not specified
                    Secondary(SecondaryNum).MaxLoad = Secondary(SecondaryNum).CoolingLoadRated;
                } // SecFluidType

                Real64 DeltaCap2 =
                    std::abs((Secondary(SecondaryNum).CoolingLoadRated - NominalSecondaryRefLoad) / Secondary(SecondaryNum).CoolingLoadRated);
                if (DeltaCap2 > (0.3)) { // diff between chiller rating and sum of nominal loads > 30%
                    ShowWarningError(
                        state,
                        format("{}=\"{}\" You may wish to check the system sizing. Total nominal refrigerating load is {:.0R} (Including cases, "
                               "walk-ins, and pump heat).  The nominal secondary loop heat exchanger capacity is {:.0R}",
                               CurrentModuleObject,
                               Secondary(SecondaryNum).Name,
                               NominalSecondaryRefLoad,
                               Secondary(SecondaryNum).CoolingLoadRated));
                }
                // compare rated xt xchanger brine flow to the total rated pump flow
                if (SecondaryFlowVolRated > (1.1 * PumpTotRatedFlowVol)) {
                    ShowWarningError(state,
                                     format("{}=\"{}\" You may wish to check the pump sizing. Total nominal brine flow is {:.0R} m3/s, but the "
                                            "total nominal pump flow rate is:  {:.0R} m3/s. ",
                                            CurrentModuleObject,
                                            Secondary(SecondaryNum).Name,
                                            SecondaryFlowVolRated,
                                            PumpTotRatedFlowVol));
                }

            } // Secondary Loops
        } //(  IF (NumSimulationSecondarySystems > 0)

        //************ END SECONDARY SYSTEM INPUT  **************

        //************ START Compressor INPUT  **************

        CurrentModuleObject = "Refrigeration:Compressor";
        for (int CompNum = 1; CompNum <= state.dataRefrigCase->NumSimulationCompressors; ++CompNum) {
            state.dataInputProcessing->inputProcessor->getObjectItem(state,
                                                                     CurrentModuleObject,
                                                                     CompNum,
                                                                     Alphas,
                                                                     NumAlphas,
                                                                     Numbers,
                                                                     NumNumbers,
                                                                     IOStatus,
                                                                     lNumericBlanks,
                                                                     lAlphaBlanks,
                                                                     cAlphaFieldNames,
                                                                     cNumericFieldNames);
            ErrorObjectHeader eoh{routineName, CurrentModuleObject, Alphas(1)};

            Compressor(CompNum).Name = Alphas(1);

            Compressor(CompNum).ElecPowerCurvePtr = Curve::GetCurveIndex(state, Alphas(2)); // convert curve name to number
            if ((!lAlphaBlanks(2)) && Compressor(CompNum).ElecPowerCurvePtr == 0) {
                ShowSevereItemNotFound(state, eoh, cAlphaFieldNames(2), Alphas(2));
                ErrorsFound = true;
            }

            Compressor(CompNum).CapacityCurvePtr = Curve::GetCurveIndex(state, Alphas(3)); // convert curve name to number
            if ((!lAlphaBlanks(3)) && Compressor(CompNum).CapacityCurvePtr == 0) {
                ShowSevereItemNotFound(state, eoh, cAlphaFieldNames(3), Alphas(3));
                ErrorsFound = true;
            }

            // Get superheat rating type (Either N1 or N2 Must be input)
            if (((!lNumericBlanks(1)) && (!lNumericBlanks(2))) || (lNumericBlanks(1) && lNumericBlanks(2))) {
                ShowSevereError(state,
                                format("{}{}=\"{}\"One, and Only One of {} or {}",
                                       RoutineName,
                                       CurrentModuleObject,
                                       Compressor(CompNum).Name,
                                       cNumericFieldNames(1),
                                       cNumericFieldNames(2)));
                ShowContinueError(state, "Must Be Entered. Check input value choices.");
                ErrorsFound = true;
            } else if (!lNumericBlanks(1)) {
                Compressor(CompNum).SuperheatRatingType = CompRatingType::Superheat;
                Compressor(CompNum).RatedSuperheat = Numbers(1);
            } else if (!lNumericBlanks(2)) {
                Compressor(CompNum).SuperheatRatingType = CompRatingType::ReturnGasTemperature;
                Compressor(CompNum).RatedSuperheat = Numbers(2);
            } // Set SuperheatRatingType

            // Get subcool rating type (Either N3 or N4 Must be input)
            if (((!lNumericBlanks(3)) && (!lNumericBlanks(4))) || (lNumericBlanks(3) && lNumericBlanks(4))) {
                ShowSevereError(state,
                                format("{}{}=\"{}\" One, and Only One of {} or {}",
                                       RoutineName,
                                       CurrentModuleObject,
                                       Compressor(CompNum).Name,
                                       cNumericFieldNames(3),
                                       cNumericFieldNames(4)));
                ShowContinueError(state, "Must Be Entered. Check input value choices.");
                ErrorsFound = true;
            } else if (!lNumericBlanks(3)) {
                Compressor(CompNum).SubcoolRatingType = CompRatingType::LiquidTemperature;
                Compressor(CompNum).RatedSubcool = Numbers(3);
            } else if (!lNumericBlanks(4)) {
                Compressor(CompNum).SubcoolRatingType = CompRatingType::Subcooling;
                Compressor(CompNum).RatedSubcool = Numbers(4);
            } // Set SubcoolRatingType

            Compressor(CompNum).EndUseSubcategory = "General";
            if (!lAlphaBlanks(4)) {
                Compressor(CompNum).EndUseSubcategory = Alphas(4);
            }

            //  If the compressor is a transcritical CO compressor, get transcritical power and capacity curves
            if (lAlphaBlanks(5)) {
                Compressor(CompNum).TransFlag = false;
                // For some reason, Alkphas(5) is not uppercased?
            } else if (CriticalType crit = static_cast<CriticalType>(getEnumValue(criticalTypeNamesUC, Util::makeUPPER(Alphas(5))));
                       crit != CriticalType::Invalid) {
                Compressor(CompNum).TransFlag = static_cast<bool>(crit);
            } else {
                ShowSevereInvalidKey(state, eoh, cAlphaFieldNames(5), Alphas(5));
                ErrorsFound = true;
            }

            if (Compressor(CompNum).TransFlag) {
                if (lAlphaBlanks(6)) {
                    ShowSevereEmptyField(state, eoh, cAlphaFieldNames(6));
                    ErrorsFound = true;
                } else if ((Compressor(CompNum).TransElecPowerCurvePtr = Curve::GetCurveIndex(state, Alphas(6))) == 0) {
                    ShowSevereItemNotFound(state, eoh, cAlphaFieldNames(6), Alphas(6));
                    ErrorsFound = true;
                }

                if (lAlphaBlanks(7)) {
                    ShowSevereEmptyField(state, eoh, cAlphaFieldNames(7));
                    ErrorsFound = true;
                } else if ((Compressor(CompNum).TransCapacityCurvePtr = Curve::GetCurveIndex(state, Alphas(7))) == 0) {
                    ShowSevereItemNotFound(state, eoh, cAlphaFieldNames(7), Alphas(7));
                    ErrorsFound = true;
                }
            } else {
                if (!lAlphaBlanks(6)) {
                    ShowWarningNonEmptyField(state, eoh, cAlphaFieldNames(6), cAlphaFieldNames(5), Alphas(5));
                }
                if (!lAlphaBlanks(7)) {
                    ShowWarningNonEmptyField(state, eoh, cAlphaFieldNames(7), cAlphaFieldNames(5), Alphas(5));
                }
            }

        } // RefrigCompressor

        //************ END Compressor INPUT         **************

        //************ START Subcooler INPUT        **************
        if (state.dataRefrigCase->NumSimulationSubcoolers > 0) {
            CurrentModuleObject = "Refrigeration:Subcooler";
            state.dataRefrigCase->NumSimulationMechSubcoolers = 0;
            for (int SubcoolerNum = 1; SubcoolerNum <= state.dataRefrigCase->NumSimulationSubcoolers; ++SubcoolerNum) {
                state.dataInputProcessing->inputProcessor->getObjectItem(state,
                                                                         CurrentModuleObject,
                                                                         SubcoolerNum,
                                                                         Alphas,
                                                                         NumAlphas,
                                                                         Numbers,
                                                                         NumNumbers,
                                                                         IOStatus,
                                                                         lNumericBlanks,
                                                                         lAlphaBlanks,
                                                                         cAlphaFieldNames,
                                                                         cNumericFieldNames);
                ErrorObjectHeader eoh{routineName, CurrentModuleObject, Alphas(1)};
                Subcooler(SubcoolerNum).Name = Alphas(1);

                // Get subcooler type
                if ((Subcooler(SubcoolerNum).subcoolerType = static_cast<SubcoolerType>(getEnumValue(subcoolerTypeNamesUC, Alphas(2)))) ==
                    SubcoolerType::Invalid) {
                    ShowSevereInvalidKey(state, eoh, cAlphaFieldNames(2), Alphas(2));
                    ErrorsFound = true;
                } else if (Subcooler(SubcoolerNum).subcoolerType == SubcoolerType::Mechanical) {
                    ++state.dataRefrigCase->NumSimulationMechSubcoolers;
                }

                switch (Subcooler(SubcoolerNum).subcoolerType) {
                case SubcoolerType::LiquidSuction: {
                    Subcooler(SubcoolerNum).LiqSuctDesignDelT = 10.0; // default value
                    if (!lNumericBlanks(1)) {
                        Subcooler(SubcoolerNum).LiqSuctDesignDelT = Numbers(1);
                    }
                    if (Subcooler(SubcoolerNum).LiqSuctDesignDelT < 0.0) {
                        ShowSevereError(state,
                                        format("{}{}=\"{}\" {} cannot be less than zero.",
                                               RoutineName,
                                               CurrentModuleObject,
                                               Subcooler(SubcoolerNum).Name,
                                               cNumericFieldNames(1)));
                        ErrorsFound = true;
                    }

                    if (!lNumericBlanks(2)) {
                        Subcooler(SubcoolerNum).LiqSuctDesignTliqIn = Numbers(2);
                    } else {
                        ShowSevereError(state,
                                        format("{}{}=\"{}\" {} must be specified.",
                                               RoutineName,
                                               CurrentModuleObject,
                                               Subcooler(SubcoolerNum).Name,
                                               cNumericFieldNames(2)));
                        ErrorsFound = true;
                    }

                    if (!lNumericBlanks(3)) {
                        Subcooler(SubcoolerNum).LiqSuctDesignTvapIn = Numbers(3);
                    } else {
                        ShowSevereError(state,
                                        format("{}{}=\"{}\" {} must be specified.",
                                               RoutineName,
                                               CurrentModuleObject,
                                               Subcooler(SubcoolerNum).Name,
                                               cNumericFieldNames(3)));
                        ErrorsFound = true;
                    }
                    if (Subcooler(SubcoolerNum).LiqSuctDesignTvapIn > Subcooler(SubcoolerNum).LiqSuctDesignTliqIn) {
                        ShowSevereError(state,
                                        format("{}{}=\"{}\" {} cannot be greater than {}.",
                                               RoutineName,
                                               CurrentModuleObject,
                                               Subcooler(SubcoolerNum).Name,
                                               cNumericFieldNames(3),
                                               cNumericFieldNames(2)));
                        ErrorsFound = true;
                    } // error check
                } break;
                case SubcoolerType::Mechanical: {
                    Subcooler(SubcoolerNum).MechSourceSys = Alphas(3);
                    // Error check on system name comes later after systems have been read

                    if (!lNumericBlanks(4)) {
                        Subcooler(SubcoolerNum).MechControlTliqOut = Numbers(4);
                    } else {
                        ShowSevereError(state,
                                        format("{}{}=\"{}\" {} must be specified.",
                                               RoutineName,
                                               CurrentModuleObject,
                                               Subcooler(SubcoolerNum).Name,
                                               cNumericFieldNames(4)));
                        ErrorsFound = true;
                    } // error check
                } break;
                default:
                    break;
                }
            } // Subcooler Input
        } // If there are subcoolers

        // ********END SUBCOOLER INPUTS ************

        //**** Read TransferLoad Lists **********************************************************
        if (state.dataRefrigCase->NumSimulationTransferLoadLists > 0) {
            CurrentModuleObject = "Refrigeration:TransferLoadList";
            for (int ListNum = 1; ListNum <= state.dataRefrigCase->NumSimulationTransferLoadLists; ++ListNum) {
                state.dataInputProcessing->inputProcessor->getObjectItem(state,
                                                                         CurrentModuleObject,
                                                                         ListNum,
                                                                         Alphas,
                                                                         NumAlphas,
                                                                         Numbers,
                                                                         NumNumbers,
                                                                         IOStatus,
                                                                         lNumericBlanks,
                                                                         lAlphaBlanks,
                                                                         cAlphaFieldNames,
                                                                         cNumericFieldNames);
                Util::IsNameEmpty(state, Alphas(1), CurrentModuleObject, ErrorsFound);

                TransferLoadList(ListNum).Name = Alphas(1);

                // Transfer load list alphas include TransferLoadList name and one name for each Secondary or Cascade Condenser in list
                // below allocates larger than needed (each allocated to sum of both), but avoids two loops through input fields
                int NumTotalLoadsOnList = NumAlphas - 1;
                if (!allocated(TransferLoadList(ListNum).CascadeLoadItemNum)) {
                    TransferLoadList(ListNum).CascadeLoadItemNum.allocate(NumTotalLoadsOnList);
                }
                if (!allocated(TransferLoadList(ListNum).SecondaryItemNum)) {
                    TransferLoadList(ListNum).SecondaryItemNum.allocate(NumTotalLoadsOnList);
                }

                int NumSecondarysOnList = 0;
                int NumCascadeLoadsOnList = 0;
                for (int NumLoad = 1; NumLoad <= NumTotalLoadsOnList; ++NumLoad) {
                    int AlphaListNum = 1 + NumLoad;
                    int LoadCascadeNum = 0;
                    int LoadSecondaryNum = 0;
                    if (state.dataRefrigCase->NumRefrigCondensers > 0) {
                        LoadCascadeNum = Util::FindItemInList(Alphas(AlphaListNum), Condenser);
                    }
                    if (state.dataRefrigCase->NumSimulationSecondarySystems > 0) {
                        LoadSecondaryNum = Util::FindItemInList(Alphas(AlphaListNum), Secondary);
                    }
                    if ((LoadCascadeNum == 0) && (LoadSecondaryNum == 0)) {
                        ShowSevereError(state,
                                        format("{}{}=\"{}\" : has an invalid value of {}",
                                               RoutineName,
                                               CurrentModuleObject,
                                               cAlphaFieldNames(AlphaListNum),
                                               Alphas(AlphaListNum)));
                        ErrorsFound = true;
                    } else if ((LoadCascadeNum != 0) && (LoadSecondaryNum != 0)) {
                        ShowSevereError(state,
                                        format("{}{}=\"{}\" : has a non-unique name : {}",
                                               RoutineName,
                                               CurrentModuleObject,
                                               cAlphaFieldNames(AlphaListNum),
                                               Alphas(AlphaListNum)));
                        ErrorsFound = true;
                    } else if (LoadCascadeNum != 0) {
                        if (Condenser(LoadCascadeNum).CondenserType != DataHeatBalance::RefrigCondenserType::Cascade) {
                            ShowSevereError(state,
                                            format("{}{}=\"{}\" : has a condenser listed as a transfer load that is not a cascade condenser: {}",
                                                   RoutineName,
                                                   CurrentModuleObject,
                                                   System(RefrigSysNum).Name,
                                                   Alphas(AlphaListNum)));
                            ErrorsFound = true;
                        } else {
                            ++NumCascadeLoadsOnList;
                            TransferLoadList(ListNum).CascadeLoadItemNum(NumCascadeLoadsOnList) = LoadCascadeNum;
                        } // /= condenser cascade type
                    } else if (LoadSecondaryNum != 0) {
                        ++NumSecondarysOnList;
                        TransferLoadList(ListNum).SecondaryItemNum(NumSecondarysOnList) = LoadSecondaryNum;
                    }
                    TransferLoadList(ListNum).NumSecondarys = NumSecondarysOnList;
                    TransferLoadList(ListNum).NumCascadeLoads = NumCascadeLoadsOnList;
                } // Num Total Loads on List
            } // ListNum=1,NumSimulationTransferLoadLists
        } //(NumSimulationTransferLoadLists > 0)

        //**** End read transfer load Lists **********************************************************

        //**** Read Compressor Lists **********************************************************
        CurrentModuleObject = "Refrigeration:CompressorList";
        for (int ListNum = 1; ListNum <= NumCompressorLists; ++ListNum) {
            state.dataInputProcessing->inputProcessor->getObjectItem(state,
                                                                     CurrentModuleObject,
                                                                     ListNum,
                                                                     Alphas,
                                                                     NumAlphas,
                                                                     Numbers,
                                                                     NumNumbers,
                                                                     IOStatus,
                                                                     lNumericBlanks,
                                                                     lAlphaBlanks,
                                                                     cAlphaFieldNames,
                                                                     cNumericFieldNames);
            CompressorLists(ListNum).NumCompressors = NumAlphas - 1;
            Util::IsNameEmpty(state, Alphas(1), CurrentModuleObject, ErrorsFound);

            CompressorLists(ListNum).Name = Alphas(1);
            if (!allocated(CompressorLists(ListNum).CompItemNum)) {
                CompressorLists(ListNum).CompItemNum.allocate(CompressorLists(ListNum).NumCompressors);
            }

            for (int CompIndex = 1; CompIndex <= CompressorLists(ListNum).NumCompressors; ++CompIndex) {
                int AlphaListNum = CompIndex + 1; // same as do loop from 2 to end of list
                if (!lAlphaBlanks(AlphaListNum)) {
                    CompressorLists(ListNum).CompItemNum(CompIndex) = Util::FindItemInList(Alphas(AlphaListNum), Compressor);
                    if (CompressorLists(ListNum).CompItemNum(CompIndex) == 0) {
                        ShowSevereError(state,
                                        format("{}{}=\"{}\", has an invalid {} defined as {}",
                                               RoutineName,
                                               CurrentModuleObject,
                                               CompressorLists(ListNum).Name,
                                               cAlphaFieldNames(AlphaListNum),
                                               Alphas(AlphaListNum)));
                        ErrorsFound = true;
                    }
                }
            } // NumCompressors in CompressorList

        } // NumCompressorLists

        // ********READ REFRIGERATION SYSTEMS  ***********

        CurrentModuleObject = "Refrigeration:System";
        for (RefrigSysNum = 1; RefrigSysNum <= state.dataRefrigCase->NumRefrigSystems; ++RefrigSysNum) {

            state.dataInputProcessing->inputProcessor->getObjectItem(state,
                                                                     CurrentModuleObject,
                                                                     RefrigSysNum,
                                                                     Alphas,
                                                                     NumAlphas,
                                                                     Numbers,
                                                                     NumNumbers,
                                                                     IOStatus,
                                                                     lNumericBlanks,
                                                                     lAlphaBlanks,
                                                                     cAlphaFieldNames,
                                                                     cNumericFieldNames);

            ErrorObjectHeader eoh{routineName, CurrentModuleObject, Alphas(1)};
            Util::IsNameEmpty(state, Alphas(1), CurrentModuleObject, ErrorsFound);

            System(RefrigSysNum).Name = Alphas(1);

            // Read all loads on this System: cases, walk-ins, cascade loads, and secondary loops
            if (lAlphaBlanks(2) && lAlphaBlanks(3)) {
                // No cases, walkins, cascade loads, or secondary loops specified, ie, System has no load
                ShowSevereError(state,
                                format("{}{}=\"{}\", has no loads, must have at least one of: {} or {} objects attached.",
                                       RoutineName,
                                       CurrentModuleObject,
                                       System(RefrigSysNum).Name,
                                       cAlphaFieldNames(2),
                                       cAlphaFieldNames(3)));
                ErrorsFound = true;
            }
            NumCases = 0;
            System(RefrigSysNum).NumCases = 0;
            int NumCoils = 0;
            System(RefrigSysNum).NumCoils = 0;
            NumWalkIns = 0;
            System(RefrigSysNum).NumWalkIns = 0;
            int NumSecondary = 0;
            System(RefrigSysNum).NumSecondarys = 0;
            System(RefrigSysNum).NumCascadeLoads = 0;
            System(RefrigSysNum).NumNonCascadeLoads = 0;
            Real64 NominalTotalCaseCap = 0.0;
            Real64 NominalTotalCoilCap = 0.0;
            Real64 NominalTotalWalkInCap = 0.0;
            Real64 NominalTotalSecondaryCap = 0.0;
            Real64 NominalTotalCoolingCap;
            Real64 NominalTotalCascadeLoad = 0.0;
            System(RefrigSysNum).RefInventory = 0.0;

            //   Check for case or walkin or CaseAndWalkInList names
            AlphaNum = 2;
            if (!lAlphaBlanks(AlphaNum)) {

                // Entry for Alphas(AlphaNum) can be either a Case, WalkIn or CaseAndWalkInList name
                int CaseAndWalkInListNum = 0;
                int CaseNum = 0;
                int WalkInNum = 0;
                int CoilNum = 0;
                if (state.dataRefrigCase->NumSimulationCaseAndWalkInLists > 0) {
                    CaseAndWalkInListNum = Util::FindItemInList(Alphas(AlphaNum), CaseAndWalkInList);
                }
                if (state.dataRefrigCase->NumSimulationCases > 0) {
                    CaseNum = Util::FindItemInList(Alphas(AlphaNum), RefrigCase);
                }
                if (state.dataRefrigCase->NumSimulationWalkIns > 0) {
                    WalkInNum = Util::FindItemInList(Alphas(AlphaNum), WalkIn);
                }
                if (state.dataRefrigCase->NumSimulationRefrigAirChillers > 0) {
                    CoilNum = Util::FindItemInList(Alphas(AlphaNum), WarehouseCoil);
                }
                int NumNameMatches = 0;
                if (CaseAndWalkInListNum != 0) {
                    ++NumNameMatches;
                }
                if (CaseNum != 0) {
                    ++NumNameMatches;
                }
                if (WalkInNum != 0) {
                    ++NumNameMatches;
                }
                if (CoilNum != 0) {
                    ++NumNameMatches;
                }

                if (NumNameMatches != 1) { // name must uniquely point to a list or a single case or walkin or coil
                    ErrorsFound = true;
                    if (NumNameMatches == 0) {
                        ShowSevereError(state,
                                        format("{}{}=\"{}\", has an invalid {}: {}",
                                               RoutineName,
                                               CurrentModuleObject,
                                               System(RefrigSysNum).Name,
                                               cAlphaFieldNames(AlphaNum),
                                               Alphas(AlphaNum)));
                    } else if (NumNameMatches > 1) {
                        ShowSevereError(state,
                                        format("{}{}=\"{}\",  has a non-unique name that could be either a {}: {}",
                                               RoutineName,
                                               CurrentModuleObject,
                                               System(RefrigSysNum).Name,
                                               cAlphaFieldNames(AlphaNum),
                                               Alphas(AlphaNum)));
                    } // num matches = 0 or > 1
                } else if (CaseAndWalkInListNum != 0) { // Name points to a CaseAndWalkInList
                    NumCases = CaseAndWalkInList(CaseAndWalkInListNum).NumCases;
                    NumWalkIns = CaseAndWalkInList(CaseAndWalkInListNum).NumWalkIns;
                    NumCoils = CaseAndWalkInList(CaseAndWalkInListNum).NumCoils;
                    System(RefrigSysNum).NumCases = NumCases;
                    System(RefrigSysNum).NumWalkIns = NumWalkIns;
                    System(RefrigSysNum).NumCoils = NumCoils;
                    if (NumCases > 0) {
                        if (!allocated(System(RefrigSysNum).CaseNum)) {
                            System(RefrigSysNum).CaseNum.allocate(NumCases);
                        }
                        System(RefrigSysNum).CaseNum({1, NumCases}) = CaseAndWalkInList(CaseAndWalkInListNum).CaseItemNum({1, NumCases});
                    }
                    if (NumCoils > 0) {
                        if (!allocated(System(RefrigSysNum).CoilNum)) {
                            System(RefrigSysNum).CoilNum.allocate(NumCoils);
                        }
                        System(RefrigSysNum).CoilNum({1, NumCoils}) = CaseAndWalkInList(CaseAndWalkInListNum).CoilItemNum({1, NumCoils});
                    }
                    if (NumWalkIns > 0) {
                        if (!allocated(System(RefrigSysNum).WalkInNum)) {
                            System(RefrigSysNum).WalkInNum.allocate(NumWalkIns);
                        }
                        System(RefrigSysNum).WalkInNum({1, NumWalkIns}) = CaseAndWalkInList(CaseAndWalkInListNum).WalkInItemNum({1, NumWalkIns});
                    }
                } else if (CaseNum != 0) { // Name points to a case
                    NumCases = 1;
                    System(RefrigSysNum).NumCases = 1;
                    if (!allocated(System(RefrigSysNum).CaseNum)) {
                        System(RefrigSysNum).CaseNum.allocate(NumCases);
                    }
                    System(RefrigSysNum).CaseNum(NumCases) = CaseNum;
                } else if (CoilNum != 0) { // Name points to a coil
                    NumCoils = 1;
                    System(RefrigSysNum).NumCoils = 1;
                    if (!allocated(System(RefrigSysNum).CoilNum)) {
                        System(RefrigSysNum).CoilNum.allocate(NumCoils);
                    }
                    System(RefrigSysNum).CoilNum(NumCoils) = CoilNum;
                } else if (WalkInNum != 0) { // Name points to a walkin
                    NumWalkIns = 1;
                    System(RefrigSysNum).NumWalkIns = 1;
                    if (!allocated(System(RefrigSysNum).WalkInNum)) {
                        System(RefrigSysNum).WalkInNum.allocate(NumWalkIns);
                    }
                    System(RefrigSysNum).WalkInNum(NumWalkIns) = WalkInNum;
                } // NumNameMatches /= 1
            } // blank input for cases, walkins, or caseandwalkinlist

            if (NumCases > 0) {
                // Find lowest design evap T
                // Sum rated capacity of all cases on system
                for (int caseIndex = 1; caseIndex <= NumCases; ++caseIndex) {
                    // mark all cases on system as used by this system - checking for unused or non-unique cases
                    int CaseNum = System(RefrigSysNum).CaseNum(caseIndex);
                    ++RefrigCase(CaseNum).NumSysAttach;
                    NominalTotalCaseCap += RefrigCase(CaseNum).DesignRatedCap;
                    System(RefrigSysNum).RefInventory += RefrigCase(CaseNum).DesignRefrigInventory;
                    if (caseIndex == 1) { // look for lowest case design evap T for system
                        System(RefrigSysNum).TEvapDesign = RefrigCase(CaseNum).EvapTempDesign;
                    } else {
                        System(RefrigSysNum).TEvapDesign = min(RefrigCase(CaseNum).EvapTempDesign, System(RefrigSysNum).TEvapDesign);
                    }
                } // CaseIndex=1,NumCases
                System(RefrigSysNum).NumNonCascadeLoads += System(RefrigSysNum).NumCases;
            } // Numcases > 0

            if (NumCoils > 0) {
                // Find lowest design evap T
                // Sum rated capacity of all Coils on system
                for (int CoilIndex = 1; CoilIndex <= NumCoils; ++CoilIndex) {
                    // mark all Coils on system as used by this system - checking for unused or non-unique Coils
                    int CoilNum = System(RefrigSysNum).CoilNum(CoilIndex);
                    ++WarehouseCoil(CoilNum).NumSysAttach;
                    NominalTotalCoilCap += WarehouseCoil(CoilNum).RatedSensibleCap;
                    System(RefrigSysNum).RefInventory += WarehouseCoil(CoilNum).DesignRefrigInventory;
                    if ((CoilIndex == 1) && (System(RefrigSysNum).NumCases == 0)) { // look for lowest Coil design evap T for system
                        System(RefrigSysNum).TEvapDesign = WarehouseCoil(CoilNum).TEvapDesign;
                    } else {
                        System(RefrigSysNum).TEvapDesign = min(WarehouseCoil(CoilNum).TEvapDesign, System(RefrigSysNum).TEvapDesign);
                    }
                } // CoilIndex=1,NumCoils
                System(RefrigSysNum).NumNonCascadeLoads += System(RefrigSysNum).NumCoils;
            } // NumCoils > 0

            if (NumWalkIns > 0) {
                for (int WalkInIndex = 1; WalkInIndex <= NumWalkIns; ++WalkInIndex) {
                    int WalkInID = System(RefrigSysNum).WalkInNum(WalkInIndex);
                    // mark all WalkIns on rack as used by this system (checking for unused or non-unique WalkIns)
                    ++WalkIn(WalkInID).NumSysAttach;
                    NominalTotalWalkInCap += WalkIn(WalkInID).DesignRatedCap;
                    System(RefrigSysNum).RefInventory += WalkIn(WalkInID).DesignRefrigInventory;
                    // Defrost capacity is treated differently by compressor racks and detailed systems,
                    //  so this value may be adjusted (or warnings issued) after the walkin is assigned
                    //  to either the rack or system.
                    // for walkins served by detailed system, need capacity for both fluid and electric types.
                    if (WalkIn(WalkInID).DefrostCapacity <= -98.0) {
                        // - 99 used as a flag for blank input error message for detailed systems
                        ShowSevereError(state,
                                        format("{}Refrigeration:WalkIn=\"{}\", Defrost capacity must be greater than or equal to 0 W for "
                                               "electric and hotfluid defrost types",
                                               RoutineName,
                                               WalkIn(WalkInID).Name));
                        ErrorsFound = true;
                    }
                    // Find design evaporating temperature for system by getting min design evap for ALL loads
                    if ((WalkInIndex == 1) && (System(RefrigSysNum).NumCases == 0) && (System(RefrigSysNum).NumCoils == 0)) {
                        // note use walk in index, not walkinid here to get
                        // first walkin on this suction group/system
                        System(RefrigSysNum).TEvapDesign = WalkIn(WalkInID).TEvapDesign;
                    } else {
                        System(RefrigSysNum).TEvapDesign = min(WalkIn(WalkInID).TEvapDesign, System(RefrigSysNum).TEvapDesign);
                    }
                } // WalkInIndex=1,NumWalkIns
                System(RefrigSysNum).NumNonCascadeLoads += System(RefrigSysNum).NumWalkIns;
            } // numwalkins > 0

            AlphaNum = 3;
            // Read Transfer Loads (Secondary and Cascade) assignments for this System ,
            //     already allow more than one mech subcooler to load onto a system so they don't need to go in list
            if (!lAlphaBlanks(AlphaNum)) {

                // Entry for Alphas(AlphaNum) can be either a Secondary, CascadeLoad name or a TransferLoadList name
                int TransferLoadListNum = 0;
                int SecondaryNum = 0;
                int CascadeLoadNum = 0;
                if (state.dataRefrigCase->NumSimulationTransferLoadLists > 0) {
                    TransferLoadListNum = Util::FindItemInList(Alphas(AlphaNum), TransferLoadList);
                }
                if (state.dataRefrigCase->NumSimulationSecondarySystems > 0) {
                    SecondaryNum = Util::FindItemInList(Alphas(AlphaNum), Secondary);
                }
                if (state.dataRefrigCase->NumRefrigCondensers > 0) {
                    CascadeLoadNum = Util::FindItemInList(Alphas(AlphaNum), Condenser);
                }
                int NumNameMatches = 0;
                if (TransferLoadListNum != 0) {
                    ++NumNameMatches;
                }
                if (SecondaryNum != 0) {
                    ++NumNameMatches;
                }
                if (CascadeLoadNum != 0) {
                    ++NumNameMatches;
                }
                int NumCascadeLoad = 0;

                if (NumNameMatches != 1) { // name must uniquely point to a list or a single transfer load
                    ErrorsFound = true;
                    if (NumNameMatches == 0) {
                        ShowSevereError(state,
                                        format("{}{}=\"{}\", has an invalid {}: {}",
                                               RoutineName,
                                               CurrentModuleObject,
                                               System(RefrigSysNum).Name,
                                               cAlphaFieldNames(AlphaNum),
                                               Alphas(AlphaNum)));
                    } else if (NumNameMatches > 1) {
                        ShowSevereError(state,
                                        format("{}{}=\"{}\", has a non-unique name that could be either a {}: {}",
                                               RoutineName,
                                               CurrentModuleObject,
                                               System(RefrigSysNum).Name,
                                               cAlphaFieldNames(AlphaNum),
                                               Alphas(AlphaNum)));
                    } // num matches = 0 or > 1
                } else if (TransferLoadListNum != 0) { // Name points to a transferLoad list
                    NumSecondary = TransferLoadList(TransferLoadListNum).NumSecondarys;
                    NumCascadeLoad = TransferLoadList(TransferLoadListNum).NumCascadeLoads;
                    System(RefrigSysNum).NumSecondarys = NumSecondary;
                    System(RefrigSysNum).NumCascadeLoads = NumCascadeLoad;
                    if (!allocated(System(RefrigSysNum).SecondaryNum)) {
                        System(RefrigSysNum).SecondaryNum.allocate(NumSecondary);
                    }
                    System(RefrigSysNum).SecondaryNum({1, NumSecondary}) = TransferLoadList(TransferLoadListNum).SecondaryItemNum({1, NumSecondary});
                    if (!allocated(System(RefrigSysNum).CascadeLoadNum)) {
                        System(RefrigSysNum).CascadeLoadNum.allocate(NumCascadeLoad);
                    }
                    System(RefrigSysNum).CascadeLoadNum({1, NumCascadeLoad}) =
                        TransferLoadList(TransferLoadListNum).CascadeLoadItemNum({1, NumCascadeLoad});
                } else if (SecondaryNum != 0) { // Name points to a secondary loop load
                    NumSecondary = 1;
                    System(RefrigSysNum).NumSecondarys = 1;
                    if (!allocated(System(RefrigSysNum).SecondaryNum)) {
                        System(RefrigSysNum).SecondaryNum.allocate(NumSecondary);
                    }
                    System(RefrigSysNum).SecondaryNum(NumSecondary) = SecondaryNum;
                } else if (CascadeLoadNum != 0) { // Name points to a cascade condenser load
                    NumCascadeLoad = 1;
                    System(RefrigSysNum).NumCascadeLoads = 1;
                    if (!allocated(System(RefrigSysNum).CascadeLoadNum)) {
                        System(RefrigSysNum).CascadeLoadNum.allocate(NumCascadeLoad);
                    }
                    System(RefrigSysNum).CascadeLoadNum(NumCascadeLoad) = CascadeLoadNum;
                } // NumNameMatches /= 1

                System(RefrigSysNum).CoilFlag = false;
                // Now need to loop through all transfer loads to see if they change the minimum required system evaporating temperature
                if (NumSecondary > 0) {
                    for (int SecondaryIndex = 1; SecondaryIndex <= NumSecondary; ++SecondaryIndex) {
                        int SecondaryID = System(RefrigSysNum).SecondaryNum(SecondaryIndex);
                        if (SecondaryIndex == 1) { // check for consistency of loads (coils calc on sys time step, all others on zone time step)
                            if (Secondary(SecondaryID).CoilFlag) {
                                System(RefrigSysNum).CoilFlag = true;
                            }
                        } else if (Secondary(SecondaryID).CoilFlag != System(RefrigSysNum).CoilFlag) {
                            ShowSevereError(
                                state,
                                format("{}{}=\"{}\", Serves an inconsistent mixture of loads. Coil-type loads are served on a different time "
                                       "step than case or walkin loads. Compare loads on system served by secondary loop \"{}",
                                       RoutineName,
                                       CurrentModuleObject,
                                       System(RefrigSysNum).Name,
                                       Secondary(SecondaryID).Name));
                            ErrorsFound = true;
                        } // check for consistency of loads (coils calc on sys time step, all others on zone time step)
                        // mark all Secondarys on system as used by this system (checking for unused or non-unique Secondarys)
                        ++Secondary(SecondaryID).NumSysAttach;
                        NominalTotalSecondaryCap += Secondary(SecondaryID).CoolingLoadRated;
                        System(RefrigSysNum).RefInventory += Secondary(SecondaryID).ChillerRefInventory;
                        // Find design evaporating temperature for system by getting min design evap for ALL loads
                        if ((SecondaryIndex == 1) && (System(RefrigSysNum).NumCases == 0) && (System(RefrigSysNum).NumCoils == 0) &&
                            (System(RefrigSysNum).NumWalkIns == 0)) {
                            // note use secondary index above, not secondaryid here to get
                            // first secondary on this suction group/system
                            // note - TMinNeeded on secondary defined by cases and walkins served by secondary, not by
                            //       the secondary's rated evaporating temperature (which is used to calc secondary heat
                            //       exchanger effectiveness with other rated values)
                            System(RefrigSysNum).TEvapDesign = Secondary(SecondaryID).TMinNeeded;
                        } else {
                            System(RefrigSysNum).TEvapDesign = min(Secondary(SecondaryID).TMinNeeded, System(RefrigSysNum).TEvapDesign);
                        }
                    } // SecondaryIndex=1,NumSecondary
                    System(RefrigSysNum).NumNonCascadeLoads += System(RefrigSysNum).NumSecondarys;
                } // numsecondary > 0

                if (NumCascadeLoad > 0) {
                    for (int cascadeLoadIndex = 1; cascadeLoadIndex <= NumCascadeLoad; ++cascadeLoadIndex) {
                        int CondID = System(RefrigSysNum).CascadeLoadNum(cascadeLoadIndex);
                        if (Condenser(CondID).CondenserType != DataHeatBalance::RefrigCondenserType::Cascade) {
                            ShowSevereError(state,
                                            format("{}{}=\"{}\", has a  {}: {} cascade load that is not a cascade condenser.",
                                                   RoutineName,
                                                   CurrentModuleObject,
                                                   System(RefrigSysNum).Name,
                                                   cAlphaFieldNames(AlphaNum),
                                                   Alphas(AlphaNum)));
                            ErrorsFound = true;
                        }
                        // For a cascade condenser, need to identify the system absorbing the heat
                        Condenser(CondID).CascadeSinkSystemID = RefrigSysNum;
                        NominalTotalCascadeLoad += Condenser(CondID).RatedCapacity;
                        // Find design evaporating temperature for system by getting min design evap for ALL loads
                        if (System(RefrigSysNum).NumNonCascadeLoads == 0) {
                            if (cascadeLoadIndex == 1) {
                                // note use cascadeload index above, not condid here to get
                                // first cascade condenser served by this suction group/system
                                System(RefrigSysNum).TEvapDesign = Condenser(CondID).CascadeRatedEvapTemp;
                            } else {
                                System(RefrigSysNum).TEvapDesign = min(Condenser(CondID).CascadeRatedEvapTemp, System(RefrigSysNum).TEvapDesign);
                            } // CascadeLoadIndex == 1
                        } else { // (NumNonCascadeLoads > 0 so initial TEvapDesign set above with those other loads)
                            if (Condenser(CondID).CascadeTempControl == CascadeCndsrTempCtrlType::TempSet) {
                                System(RefrigSysNum).TEvapDesign = min(Condenser(CondID).CascadeRatedEvapTemp,
                                                                       System(RefrigSysNum).TEvapDesign); // other wise TEvapDesign set by other loads
                            }
                        }
                    } // CascadeLoadIndex=1,NumCascadeLoad
                } // CascadeLoadNum > 0
            } // yes/no blank input for transfer loads

            // check for consistency of loads (coils calc on sys time step, all others on zone time step, so can't mix on one system)
            if (System(RefrigSysNum).CoilFlag) { // could already be true if serving secondary that serves coils
                if ((System(RefrigSysNum).NumCases > 0) || (System(RefrigSysNum).NumWalkIns > 0)) {
                    ShowSevereError(state,
                                    format("{}{}=\"{}\", Serves an inconsistent mixture of loads. Coil-type loads are served on a different time "
                                           "step than case or walkin loads.",
                                           RoutineName,
                                           CurrentModuleObject,
                                           System(RefrigSysNum).Name));
                    ErrorsFound = true;
                }
            } else {                                     // no coils on secondary or no secondary
                if (System(RefrigSysNum).NumCoils > 0) { //(note, coilflag set to .FALSE. for all systems as default above
                    System(RefrigSysNum).CoilFlag = true;
                    if ((System(RefrigSysNum).NumCases > 0) || (System(RefrigSysNum).NumWalkIns > 0)) {
                        ShowSevereError(state,
                                        format("{}{}=\"{}\", Serves an inconsistent mixture of loads. Coil-type loads are served on a different "
                                               "time step than case or walkin loads.",
                                               RoutineName,
                                               CurrentModuleObject,
                                               System(RefrigSysNum).Name));
                        ErrorsFound = true;
                    }
                } // NumCoils > 0
            } // Coil flag already true due to secondary coil loads

            NominalTotalCoolingCap = NominalTotalCaseCap + NominalTotalWalkInCap + NominalTotalSecondaryCap + NominalTotalCascadeLoad;

            // read condenser
            // currently assumes one condenser per refrigeration system and but multiple systems allowed per condenser
            AlphaNum = 4;
            int NumCondensers = 1;
            if (!allocated(System(RefrigSysNum).CondenserNum)) {
                System(RefrigSysNum).CondenserNum.allocate(NumCondensers);
            }
            System(RefrigSysNum).NumCondensers = 1;
            // Find condenser number, note condensers were read in one of four objects, but all read into same list
            int CondNum = Util::FindItemInList(Alphas(AlphaNum), Condenser);
            if (CondNum == 0) {
                ShowSevereError(state,
                                format("{}{}=\"{}\", has an invalid {} defined as {}",
                                       RoutineName,
                                       CurrentModuleObject,
                                       System(RefrigSysNum).Name,
                                       cAlphaFieldNames(AlphaNum),
                                       Alphas(AlphaNum)));
                ErrorsFound = true;
            } else {
                System(RefrigSysNum).CondenserNum(NumCondensers) = CondNum;
                // Now take care of case where multiple systems share a condenser
                ++Condenser(CondNum).NumSysAttach;
                Condenser(CondNum).SysNum(Condenser(CondNum).NumSysAttach) = RefrigSysNum;
            }

            System(RefrigSysNum).RefInventory +=
                Condenser(CondNum).RefReceiverInventory + Condenser(CondNum).RefPipingInventory + Condenser(CondNum).RefOpCharge;
            if (Condenser(CondNum).CondenserType == DataHeatBalance::RefrigCondenserType::Cascade) {
                Condenser(CondNum).CascadeSysID = RefrigSysNum;
            }
            if ((Condenser(CondNum).CondenserType == DataHeatBalance::RefrigCondenserType::Air) && (Condenser(CondNum).CondenserRejectHeatToZone)) {
                System(RefrigSysNum).SystemRejectHeatToZone = true;
            }

            // Now do evaporative condenser auto-sizing because it is a function of the system's cooling load
            if (Condenser(CondNum).CondenserType == DataHeatBalance::RefrigCondenserType::Evap) {
                if (Condenser(CondNum).RatedAirFlowRate == Constant::AutoCalculate) {
                    Condenser(CondNum).RatedAirFlowRate = AirVolRateEvapCond * Condenser(CondNum).RatedCapacity;
                }
                if (Condenser(CondNum).RatedAirFlowRate <= 0.0) {
                    ShowSevereError(state,
                                    format("{}{}=\"{}\", Evaporative Condenser Air Volume Flow Rate cannot be less than or equal to zero.",
                                           RoutineName,
                                           CurrentModuleObject,
                                           Condenser(CondNum).Name));
                    ErrorsFound = true;
                }
                if (Condenser(CondNum).EvapPumpPower == Constant::AutoCalculate) {
                    Condenser(CondNum).EvapPumpPower = CondPumpRatePower * Condenser(CondNum).RatedCapacity;
                }
                if (Condenser(CondNum).EvapPumpPower < 0.0) {
                    ShowSevereError(state,
                                    format("{}{}=\"{}\", Design Evaporative Condenser Water Pump Power cannot be less than zero.",
                                           RoutineName,
                                           CurrentModuleObject,
                                           Condenser(CondNum).Name));
                    ErrorsFound = true;
                }
            }

            // Read the compressor data.
            // If the system consists of two stages of compression, these compressors will be the low-stage compressors.
            AlphaNum = 5;
            int NumCompressorsSys = 0;
            if (lAlphaBlanks(AlphaNum)) {
                // blank input where must have compressor or compressor list input.
                ShowSevereError(state, format("{}{} {}\" : must be input.", RoutineName, CurrentModuleObject, cAlphaFieldNames(AlphaNum)));
                ErrorsFound = true;
            } else { //     Entry for Alphas(AlphaNum) can be either a compressor name or a compressorlist name
                int ListNum;
                if (NumCompressorLists > 0) {
                    ListNum = Util::FindItemInList(Alphas(AlphaNum), CompressorLists);
                } else {
                    ListNum = 0;
                }
                int CompNum;
                if (state.dataRefrigCase->NumSimulationCompressors > 0) {
                    CompNum = Util::FindItemInList(Alphas(AlphaNum), Compressor);
                } else {
                    CompNum = 0;
                }
                if ((ListNum == 0) && (CompNum == 0)) { // name doesn't match either a compressor or a compressor list
                    ShowSevereError(state,
                                    format("{}{} {}, has an invalid or undefined value=\"{}\".",
                                           RoutineName,
                                           CurrentModuleObject,
                                           cAlphaFieldNames(AlphaNum),
                                           Alphas(AlphaNum)));
                    ErrorsFound = true;
                } else if ((ListNum != 0) && (CompNum != 0)) { // have compressor list and compressor with same name
                    ShowSevereError(state,
                                    format("{}{} {}, has a non-unique name used for both Compressor and CompressorList name: \"{}\".",
                                           RoutineName,
                                           CurrentModuleObject,
                                           cAlphaFieldNames(AlphaNum),
                                           Alphas(AlphaNum)));
                    ErrorsFound = true;
                } else if (ListNum != 0) {
                    NumCompressorsSys = CompressorLists(ListNum).NumCompressors;
                    System(RefrigSysNum).NumCompressors = NumCompressorsSys;
                    if (!allocated(System(RefrigSysNum).CompressorNum)) {
                        System(RefrigSysNum).CompressorNum.allocate(NumCompressorsSys);
                    }
                    System(RefrigSysNum).CompressorNum({1, NumCompressorsSys}) = CompressorLists(ListNum).CompItemNum({1, NumCompressorsSys});
                } else if (CompNum != 0) {
                    NumCompressorsSys = 1;
                    System(RefrigSysNum).NumCompressors = 1;
                    if (!allocated(System(RefrigSysNum).CompressorNum)) {
                        System(RefrigSysNum).CompressorNum.allocate(NumCompressorsSys);
                    }
                    System(RefrigSysNum).CompressorNum(NumCompressorsSys) = CompNum;
                }
            }

            if (!lNumericBlanks(1)) {
                System(RefrigSysNum).TCondenseMin = Numbers(1);
                System(RefrigSysNum).TCondenseMinInput = System(RefrigSysNum).TCondenseMin;
                if (state.dataGlobal->AnyEnergyManagementSystemInModel) {
                    SetupEMSActuator(state,
                                     "Refrigeration:System",
                                     System(RefrigSysNum).Name,
                                     "Minimum Condensing Temperature",
                                     "[C]",
                                     System(RefrigSysNum).EMSOverrideOnTCondenseMin,
                                     System(RefrigSysNum).EMSOverrideValueTCondenseMin);
                }
            } else {
                ShowSevereError(
                    state,
                    format("{}{}=\"{}\", {} must be defined.", RoutineName, CurrentModuleObject, System(RefrigSysNum).Name, cNumericFieldNames(1)));
                ErrorsFound = true;
            }
            if ((Condenser(CondNum).CondenserType == DataHeatBalance::RefrigCondenserType::Cascade) &&
                (System(RefrigSysNum).TCondenseMin > Condenser(CondNum).RatedTCondense)) {
                ShowWarningError(state,
                                 format("{}=\"{}\", The system specified minimum condensing temperature is greater than the rated condensing "
                                        "temperature for the cascade condenser. ",
                                        CurrentModuleObject,
                                        System(RefrigSysNum).Name));
            }

            AlphaNum = 6;
            System(RefrigSysNum).RefrigerantName = Alphas(AlphaNum);
            if (System(RefrigSysNum).RefrigerantName.empty()) {
                ShowSevereEmptyField(state, eoh, Alphas(AlphaNum));
                ErrorsFound = true;
            } else if ((System(RefrigSysNum).refrig = Fluid::GetRefrig(state, System(RefrigSysNum).RefrigerantName)) == nullptr) {
                ShowSevereItemNotFound(state, eoh, cAlphaFieldNames(AlphaNum), Alphas(AlphaNum));
                ErrorsFound = true;
            }
            // error messages for refrigerants already found in fluidproperties

            AlphaNum = 7;
            if (lAlphaBlanks(AlphaNum)) {
                System(RefrigSysNum).CompSuctControl = CompressorSuctionPressureCtrl::ConstantSuctionTemperature; // Default for blank
            } else if ((System(RefrigSysNum).CompSuctControl = static_cast<CompressorSuctionPressureCtrl>(
                            getEnumValue(compressorSuctionPressureCtrlNamesUC, Alphas(AlphaNum)))) == CompressorSuctionPressureCtrl::Invalid) {
                ShowSevereInvalidKey(state, eoh, cAlphaFieldNames(AlphaNum), Alphas(AlphaNum));
                ErrorsFound = true;
            } else if (System(RefrigSysNum).CompSuctControl == CompressorSuctionPressureCtrl::FloatSuctionTemperature &&
                       System(RefrigSysNum).CoilFlag) {
                ShowWarningError(state,
                                 format("{}=\"{}\", The system specified a FloatSuctionTemperature, but that is not available with air "
                                        "chiller loads so ConstantSuctionTemperature will be used. ",
                                        CurrentModuleObject,
                                        System(RefrigSysNum).Name));
            }

            // Count subcoolers on system and allocate
            AlphaNum = 8;
            System(RefrigSysNum).NumSubcoolers = 0;
            if (!lAlphaBlanks(AlphaNum)) {
                ++System(RefrigSysNum).NumSubcoolers;
            }
            if (!lAlphaBlanks(AlphaNum + 1)) {
                ++System(RefrigSysNum).NumSubcoolers;
            }

            if (System(RefrigSysNum).NumSubcoolers > 0) {
                if (!allocated(System(RefrigSysNum).SubcoolerNum)) {
                    System(RefrigSysNum).SubcoolerNum.allocate(System(RefrigSysNum).NumSubcoolers);
                }
                int NumSubcooler = 1;
                if (!lAlphaBlanks(AlphaNum)) {
                    System(RefrigSysNum).SubcoolerNum(NumSubcooler) =
                        state.dataInputProcessing->inputProcessor->getObjectItemNum(state, "Refrigeration:Subcooler", Alphas(AlphaNum));
                    if (System(RefrigSysNum).SubcoolerNum(NumSubcooler) <= 0) {
                        ShowSevereError(state,
                                        format(R"({}{}="{}", has an invalid {} defined as "{}".)",
                                               RoutineName,
                                               CurrentModuleObject,
                                               System(RefrigSysNum).Name,
                                               cAlphaFieldNames(AlphaNum),
                                               Alphas(AlphaNum)));
                        ErrorsFound = true;
                    } else {
                        Subcooler(System(RefrigSysNum).SubcoolerNum(NumSubcooler)).CoilFlag = System(RefrigSysNum).CoilFlag;
                    }
                    ++NumSubcooler;
                }
                if (!lAlphaBlanks(AlphaNum + 1)) {
                    System(RefrigSysNum).SubcoolerNum(NumSubcooler) =
                        state.dataInputProcessing->inputProcessor->getObjectItemNum(state, "Refrigeration:Subcooler", Alphas(AlphaNum + 1));
                    if (System(RefrigSysNum).SubcoolerNum(NumSubcooler) <= 0) {
                        ShowSevereError(state,
                                        format(R"({}{}="{}", has an invalid {} defined as "{}".)",
                                               RoutineName,
                                               CurrentModuleObject,
                                               System(RefrigSysNum).Name,
                                               cAlphaFieldNames(AlphaNum + 1),
                                               Alphas(AlphaNum + 1)));
                        ErrorsFound = true;
                    } else {
                        Subcooler(System(RefrigSysNum).SubcoolerNum(NumSubcooler)).CoilFlag = System(RefrigSysNum).CoilFlag;
                    }
                }
            }

            // Suction piping heat gain - optional
            //  Input UA and identify the Zone containing the bulk of the suction piping
            //  This Zone ID will be used to determine the temperature used for suction piping heat gain.
            //  The pipe heat gains are also counted as cooling credit for the zone.
            //  Zone Id is only required if Sum UA Suction Piping >0.0
            //  Get the Zone and zone node numbers from the zone name entered by the user
            AlphaNum = 10;
            System(RefrigSysNum).SumUASuctionPiping = 0.0;
            if (!lNumericBlanks(2) && !lAlphaBlanks(AlphaNum)) {
                System(RefrigSysNum).SumUASuctionPiping = Numbers(2);
                System(RefrigSysNum).SuctionPipeActualZoneNum = Util::FindItemInList(Alphas(AlphaNum), state.dataHeatBal->Zone);
                System(RefrigSysNum).SuctionPipeZoneNodeNum =
                    DataZoneEquipment::GetSystemNodeNumberForZone(state, System(RefrigSysNum).SuctionPipeActualZoneNum);
                if (System(RefrigSysNum).SuctionPipeZoneNodeNum == 0) {
                    ShowSevereError(
                        state,
                        format("{}{}=\"{}\", System Node Number not found for {} = {} even though {} is greater than zero. Suction piping heat gain "
                               "cannot be calculated unless a Zone is defined to determine the environmental temperature surrounding the piping.",
                               RoutineName,
                               CurrentModuleObject,
                               System(RefrigSysNum).Name,
                               cAlphaFieldNames(AlphaNum),
                               Alphas(AlphaNum),
                               cNumericFieldNames(2)));
                    ErrorsFound = true;
                } else {
                    state.dataRefrigCase->RefrigPresentInZone(System(RefrigSysNum).SuctionPipeActualZoneNum) = true;
                }
            } else if (!lNumericBlanks(2) && lAlphaBlanks(AlphaNum)) {
                ShowWarningError(state,
                                 format("{}{}=\"{}\" {} not found even though {} is greater than zero. Suction piping heat gain will not be "
                                        "calculated unless a Zone is defined to determine the environmental temperature surrounding the piping.",
                                        RoutineName,
                                        CurrentModuleObject,
                                        System(RefrigSysNum).Name,
                                        cAlphaFieldNames(AlphaNum),
                                        cNumericFieldNames(2)));
            } else if (lNumericBlanks(2) && !lAlphaBlanks(AlphaNum)) {
                ShowWarningError(state,
                                 format("{}{}=\"{}\" {} will not be used and suction piping heat gain will not be calculated because {} was blank.",
                                        RoutineName,
                                        CurrentModuleObject,
                                        System(RefrigSysNum).Name,
                                        cAlphaFieldNames(AlphaNum),
                                        cNumericFieldNames(2)));
            } // suction piping heat gains

            AlphaNum = 11;
            if (!lAlphaBlanks(AlphaNum)) {
                System(RefrigSysNum).EndUseSubcategory = Alphas(AlphaNum);
            }

            // Single-stage or two-stage compression system
            if (!lNumericBlanks(3)) {
                System(RefrigSysNum).NumStages = Numbers(3);
                if (System(RefrigSysNum).NumStages < 1 || System(RefrigSysNum).NumStages > 2) {
                    ShowSevereError(state,
                                    format("{}{}=\"{}\", {}{}",
                                           RoutineName,
                                           CurrentModuleObject,
                                           System(RefrigSysNum).Name,
                                           cNumericFieldNames(3),
                                           R"( has an invalid value.  Only \"1\" or \"2\" compressor stages are allowed.)"));
                    ErrorsFound = true;
                }
            } else {
                System(RefrigSysNum).NumStages = 1; // Default for blank
            }

            // Intercooler type
            // None (0) for single-stage compression systems
            // Flash intercooler (1) or coil-and-shell intercooler (2) for two-stage compression systems
            AlphaNum = 12;
            if (lAlphaBlanks(AlphaNum)) {
                System(RefrigSysNum).intercoolerType = IntercoolerType::None; // Default for blank
            } else if ((System(RefrigSysNum).intercoolerType =
                            static_cast<IntercoolerType>(getEnumValue(intercoolerTypeNamesUC, Alphas(AlphaNum)))) == IntercoolerType::Invalid) {
                ShowSevereInvalidKey(state, eoh, cAlphaFieldNames(AlphaNum), Alphas(AlphaNum));
                ErrorsFound = true;
            }

            if (System(RefrigSysNum).NumStages == 1 && (System(RefrigSysNum).intercoolerType == IntercoolerType::Flash ||
                                                        System(RefrigSysNum).intercoolerType == IntercoolerType::ShellAndCoil)) {
                ShowSevereError(
                    state, format("{}{}=\"{}\", A single-stage compression system", RoutineName, CurrentModuleObject, System(RefrigSysNum).Name));
                ShowContinueError(state, "has been specified with an intercooler.  Verify that the number of compressor stages");
                ShowContinueError(state, "and the intercooler type are consistent.");
                ErrorsFound = true;
            } else if (System(RefrigSysNum).NumStages == 2 && System(RefrigSysNum).intercoolerType == IntercoolerType::None) {
                ShowSevereError(state,
                                format("{}{}=\"{}\", A two-stage compression system", RoutineName, CurrentModuleObject, System(RefrigSysNum).Name));
                ShowContinueError(state, "has been specified without an intercooler.  Verify that the number of compressor stages");
                ShowContinueError(state, "and the intercooler type are consistent.");
                ErrorsFound = true;
            }

            // Shell-and-coil intercooler effectiveness
            if (!lNumericBlanks(4)) {
                System(RefrigSysNum).IntercoolerEffectiveness = Numbers(4);
                if (System(RefrigSysNum).IntercoolerEffectiveness < 0.0 || System(RefrigSysNum).IntercoolerEffectiveness > 1.0) {
                    ShowWarningError(state,
                                     format("{}{}=\"{}\", The specified value for the", RoutineName, CurrentModuleObject, System(RefrigSysNum).Name));
                    ShowContinueError(
                        state,
                        format("{} = {:.2R} is invalid.  This value must be", cNumericFieldNames(4), System(RefrigSysNum).IntercoolerEffectiveness));
                    ShowContinueError(state, "between 0.0 and 1.0.  The default value of 0.8 will be used.");
                    System(RefrigSysNum).IntercoolerEffectiveness = 0.8;
                }
            } else {
                System(RefrigSysNum).IntercoolerEffectiveness = 0.8;
            }

            // Read the high-stage compressor info, if two-stage compression has been specified.
            AlphaNum = 13;
            int NumHiStageCompressorsSys = 0;
            if (System(RefrigSysNum).NumStages == 2) {
                if (lAlphaBlanks(AlphaNum)) {
                    // blank input where must have high-stage compressor or compressor list input.
                    ShowSevereError(state,
                                    format("{}{}=\"{}\", {} must be input for two-stage compression systems.",
                                           RoutineName,
                                           CurrentModuleObject,
                                           System(RefrigSysNum).Name,
                                           cAlphaFieldNames(AlphaNum)));
                    ErrorsFound = true;
                } else { //     Entry for Alphas(AlphaNum) can be either a compressor name or a compressorlist name
                    int ListNum = Util::FindItemInList(Alphas(AlphaNum), CompressorLists);
                    int CompNum = Util::FindItemInList(Alphas(AlphaNum), Compressor);
                    if ((ListNum == 0) && (CompNum == 0)) { // name doesn't match either a compressor or a compressor list
                        ShowSevereError(state,
                                        format(R"({}{}="{}", {} has an invalid or undefined value="{}".)",
                                               RoutineName,
                                               CurrentModuleObject,
                                               System(RefrigSysNum).Name,
                                               cAlphaFieldNames(AlphaNum),
                                               Alphas(AlphaNum)));
                        ErrorsFound = true;
                    } else if ((ListNum != 0) && (CompNum != 0)) { // have compressor list and compressor with same name
                        ShowSevereError(state,
                                        format(R"({}{}="{}", {} has a non-unique name used for both Compressor and CompressorList name: "{}".)",
                                               RoutineName,
                                               CurrentModuleObject,
                                               System(RefrigSysNum).Name,
                                               cAlphaFieldNames(AlphaNum),
                                               Alphas(AlphaNum)));
                        ErrorsFound = true;
                    } else if (ListNum != 0) {
                        NumHiStageCompressorsSys = CompressorLists(ListNum).NumCompressors;
                        System(RefrigSysNum).NumHiStageCompressors = NumHiStageCompressorsSys;
                        if (!allocated(System(RefrigSysNum).HiStageCompressorNum)) {
                            System(RefrigSysNum).HiStageCompressorNum.allocate(NumHiStageCompressorsSys);
                        }
                        System(RefrigSysNum).HiStageCompressorNum({1, NumHiStageCompressorsSys}) =
                            CompressorLists(ListNum).CompItemNum({1, NumHiStageCompressorsSys});
                    } else if (CompNum != 0) {
                        NumHiStageCompressorsSys = 1;
                        System(RefrigSysNum).NumHiStageCompressors = 1;
                        if (!allocated(System(RefrigSysNum).HiStageCompressorNum)) {
                            System(RefrigSysNum).HiStageCompressorNum.allocate(NumHiStageCompressorsSys);
                        }
                        System(RefrigSysNum).HiStageCompressorNum(NumHiStageCompressorsSys) = CompNum;
                    }
                }
            }

            // Determine intercooler pressure and temperature at design conditions
            if (System(RefrigSysNum).NumStages == 2) {
                Real64 PCond =
                    System(RefrigSysNum).refrig->getSatPressure(state, Condenser(System(RefrigSysNum).CondenserNum(1)).RatedTCondense, RoutineName);
                Real64 PEvap = System(RefrigSysNum).refrig->getSatPressure(state, System(RefrigSysNum).TEvapDesign, RoutineName);
                System(RefrigSysNum).PIntercooler = std::sqrt(PCond * PEvap);
                System(RefrigSysNum).TIntercooler =
                    System(RefrigSysNum).refrig->getSatTemperature(state, System(RefrigSysNum).PIntercooler, RoutineName);
            } // NumStages

            // Sum capacity of single-stage compressors or low-stage compressors if two-stage system
            Real64 NominalTotalCompCap = 0.0;
            for (int CompIndex = 1; CompIndex <= NumCompressorsSys; ++CompIndex) {
                int CompNum = System(RefrigSysNum).CompressorNum(CompIndex);
                if (!Compressor(CompNum).TransFlag) {          //  Subcritical Compressor
                    if (System(RefrigSysNum).NumStages == 1) { //  Single-stage compression
                        Compressor(CompNum).NomCap = Curve::CurveValue(state,
                                                                       Compressor(CompNum).CapacityCurvePtr,
                                                                       System(RefrigSysNum).TEvapDesign,
                                                                       Condenser(System(RefrigSysNum).CondenserNum(1)).RatedTCondense);
                        NominalTotalCompCap += Compressor(CompNum).NomCap;
                        ++Compressor(CompNum).NumSysAttach;
                    } else { //  Two-stage compression, low-stage compressors
                        Compressor(CompNum).NomCap = Curve::CurveValue(
                            state, Compressor(CompNum).CapacityCurvePtr, System(RefrigSysNum).TEvapDesign, System(RefrigSysNum).TIntercooler);
                        NominalTotalCompCap += Compressor(CompNum).NomCap;
                        ++Compressor(CompNum).NumSysAttach;
                    } // NumStages
                } else { //  Transcritical compressor attached to subcritical refrigeration cycle
                    ShowSevereError(state,
                                    format("{}{}. A transcritical compressor is attached to a subcritical refrigeration system.",
                                           RoutineName,
                                           CurrentModuleObject));
                    ShowContinueError(state,
                                      "Check input to ensure that subcritical compressors are connected only to subcritical systems and "
                                      "transcritical compressors are connected only to transcritical systems.");
                    ErrorsFound = true;
                } // .NOT. Compressor(CompNum)%TransFlag
            }

            Real64 NominalTotalHiStageCompCap(0.0); // Total of nominal high-stage compressor capacities, used for rough input check (W)

            // Sum capacity of high-stage compressors if two stage system
            if (System(RefrigSysNum).NumStages == 2) {
                for (int CompIndex = 1; CompIndex <= NumHiStageCompressorsSys; ++CompIndex) {
                    int CompNum = System(RefrigSysNum).HiStageCompressorNum(CompIndex);
                    if (!Compressor(CompNum).TransFlag) { //  Subcritical Compressor
                        Compressor(CompNum).NomCap = Curve::CurveValue(state,
                                                                       Compressor(CompNum).CapacityCurvePtr,
                                                                       System(RefrigSysNum).TIntercooler,
                                                                       Condenser(System(RefrigSysNum).CondenserNum(1)).RatedTCondense);
                        NominalTotalHiStageCompCap += Compressor(CompNum).NomCap;
                        ++Compressor(CompNum).NumSysAttach;
                    } else { //  Transcritical compressor attached to subcritical refrigeration cycle
                        ShowSevereError(state,
                                        format("{}{}. A transcritical compressor is attached to a subcritical refrigeration system.",
                                               RoutineName,
                                               CurrentModuleObject));
                        ShowContinueError(state,
                                          "Check input to ensure that subcritical compressors are connected only to subcritical systems and "
                                          "transcritical compressors are connected only to transcritical systems.");
                        ErrorsFound = true;
                    }
                }
            } // NumStages

            // Compare the rated capacity of compressor, condenser, and cases.
            // Note, rated capacities can be far off from operating capacities, but rough check.
            Real64 NominalCondCap = Condenser(System(RefrigSysNum).CondenserNum(1)).RatedCapacity;
            if (System(RefrigSysNum).SystemRejectHeatToZone) {
                NominalCondCap *= 2.0;
            }
            if (System(RefrigSysNum).NumStages == 1) { // Single-stage system
                if ((NominalTotalCompCap < (0.7 * NominalTotalCoolingCap)) || (NominalCondCap < (1.3 * NominalTotalCoolingCap))) {
                    ShowWarningError(state,
                                     format("{}=\"{}\", You may wish to check the system sizing. Total nominal cooling capacity is {:.0R}W. "
                                            "Condenser capacity is {:.0R}W. Nominal compressor capacity is {:.0R}W.",
                                            CurrentModuleObject,
                                            System(RefrigSysNum).Name,
                                            NominalTotalCoolingCap,
                                            NominalCondCap,
                                            NominalTotalCompCap));
                }
            } else if (System(RefrigSysNum).NumStages == 2) { // Two-stage system
                if ((NominalTotalHiStageCompCap < (0.7 * NominalTotalCoolingCap)) || (NominalCondCap < (1.3 * NominalTotalCoolingCap))) {
                    ShowWarningError(state,
                                     format("{}=\"{}\", You may wish to check the system sizing. Total nominal cooling capacity is {:.0R}W. "
                                            "Condenser capacity is {:.0R}W. Nominal compressor capacity is {:.0R}W.",
                                            CurrentModuleObject,
                                            System(RefrigSysNum).Name,
                                            NominalTotalCoolingCap,
                                            NominalCondCap,
                                            NominalTotalCompCap));
                }
            } // NumStages

        } // Refrigeration systems

        // Assign coilflags to compressors, condensers, and subcoolers (coils calc on sys time step, all other refrig loads on zone time step, so
        // can't mix on one system) need to do here once again after all cascade condensers and cascade sink systems have been identified
        for (RefrigSysNum = 1; RefrigSysNum <= state.dataRefrigCase->NumRefrigSystems; ++RefrigSysNum) {
            // assign flags to all condensers to match system below condenser (system rejecting heat to cascade condenser)
            int CondNum = System(RefrigSysNum).CondenserNum(1); // right now only have one condenser per system
            Condenser(CondNum).CoilFlag = System(RefrigSysNum).CoilFlag;
            for (int CompIndex = 1; CompIndex <= System(RefrigSysNum).NumCompressors; ++CompIndex) {
                int CompNum = System(RefrigSysNum).CompressorNum(CompIndex);
                Compressor(CompNum).CoilFlag = System(RefrigSysNum).CoilFlag;
            }

        } // assign coil flags to all condensers

        // Finished setting cascade condenser coilflags to match system rejecting heat to the cascade condenser
        // Now have to see if there's a mismatch in the coilflag with the system absorbing heat from the cascade condenser
        // Note a system can cool multiple cascade condensers.  If so, need to be sure all are consistent - all coil or all non-coil(called case
        // here) check for consistency of loads (coils calc on sys time step, all others on zone time step, so can't mix on one system)
        for (RefrigSysNum = 1; RefrigSysNum <= state.dataRefrigCase->NumRefrigSystems;
             ++RefrigSysNum) { // check flags for systems reflect all cascade loads
            if (System(RefrigSysNum).NumCascadeLoads == 0) {
                continue;
            }
            if (System(RefrigSysNum).CoilFlag) { // system already identified as serving coils
                for (int CondID = 1; CondID <= state.dataRefrigCase->NumRefrigCondensers; ++CondID) {
                    if (Condenser(CondID).CondenserType != DataHeatBalance::RefrigCondenserType::Cascade) {
                        continue;
                    }
                    if (RefrigSysNum != Condenser(CondID).CascadeSinkSystemID) {
                        continue; // this condenser is not a cascade load on this system
                    }
                    if (!Condenser(CondID).CoilFlag) {
                        // would mean system already serving coil loads and this condenser cooling system with case-type loads
                        ShowSevereError(state,
                                        format("{}{}=\"{}\", Serves an inconsistent mixture of loads. Coil-type loads are served on a different "
                                               "time step than case or walkin loads. Compare loads on system served by cascade condenser \"{}",
                                               RoutineName,
                                               CurrentModuleObject,
                                               System(RefrigSysNum).Name,
                                               Condenser(CondID).Name));
                        ErrorsFound = true;
                    }
                } // CondID
            } else { // %coilflag == false, so no coil loads prev identified directly or through secondary loop
                // Flag to help verify load type with loads served by systems cooled by cascade condensers
                bool CaseLoads = false;
                int NumCascadeLoadsChecked = 0;
                for (int CondID = 1; CondID <= state.dataRefrigCase->NumRefrigCondensers; ++CondID) { // look at All cascade condenser loads on system
                    if (Condenser(CondID).CondenserType != DataHeatBalance::RefrigCondenserType::Cascade) {
                        continue;
                    }
                    if (RefrigSysNum != Condenser(CondID).CascadeSinkSystemID) {
                        continue; // this condenser is not a cascade load on this system
                    }
                    ++NumCascadeLoadsChecked;
                    if ((CaseLoads) && (!Condenser(CondID).CoilFlag) && (!System(RefrigSysNum).CoilFlag)) {
                        continue;
                    }
                    // all loads to date are case-type and properly flagged with consistent coilflags
                    //(note caseloads could be true if prev cascade load checked is serving a case-type system)
                    if (NumCascadeLoadsChecked == 1) {
                        if (Condenser(CondID).CoilFlag) {
                            System(RefrigSysNum).CoilFlag = true;
                            // setting system coilflag if 1st cascade condenser served has coils (system has no case-type loads up to this point)
                        } else { // condenser is not serving coils, but case-type loads
                            CaseLoads = true;
                            // system coilflag already set to false
                        } // Condenser%CoilFlag
                    } else { // numcascadeloadschecked > 1
                        if (System(RefrigSysNum).CoilFlag != Condenser(CondID).CoilFlag) {
                            ShowSevereError(
                                state,
                                format("{}{}=\"{}\", Serves an inconsistent mixture of loads. Coil-type loads are served on a different time "
                                       "step than case or walkin loads. Compare loads on system served by cascade condenser \"{}",
                                       RoutineName,
                                       CurrentModuleObject,
                                       System(RefrigSysNum).Name,
                                       Condenser(CondID).Name));
                            ErrorsFound = true;
                        }
                    } // numcascadeloadschecked > 1
                } // CondID
            } //(System%coilflag)
        } // Refrigeration systems checking coilflag consistency with cascade condenser loads

    } //(NumRefrigSystems > 0)

    // after the systems have been read, can finish the mechanical subcooler/system interactions
    // System%NumMechSCServed=0
    if (state.dataRefrigCase->NumSimulationSubcoolers > 0) {
        for (int SubcoolerNum = 1; SubcoolerNum <= state.dataRefrigCase->NumSimulationSubcoolers; ++SubcoolerNum) {
            if (Subcooler(SubcoolerNum).subcoolerType == SubcoolerType::LiquidSuction) {
                continue;
            }
            Subcooler(SubcoolerNum).MechSourceSysID =
                state.dataInputProcessing->inputProcessor->getObjectItemNum(state, "Refrigeration:System", Subcooler(SubcoolerNum).MechSourceSys);
            if (Subcooler(SubcoolerNum).MechSourceSysID == 0) {
                ShowSevereError(state,
                                format(R"({}{}="{}", Mechanical Subcooler has an invalid Source Refrigeration:System="{}".)",
                                       RoutineName,
                                       CurrentModuleObject,
                                       Subcooler(SubcoolerNum).Name,
                                       Subcooler(SubcoolerNum).MechSourceSys));
                ErrorsFound = true;
            } else {
                if (System(Subcooler(SubcoolerNum).MechSourceSysID).CoilFlag != Subcooler(SubcoolerNum).CoilFlag) {
                    ShowSevereError(state,
                                    format("{}{}=\"{}\", Serves an inconsistent mixture of loads. Coil-type loads are served on a different time "
                                           "step than case or walkin loads. Compare loads on system served by mechanical subcooler \"{}",
                                           RoutineName,
                                           CurrentModuleObject,
                                           System(RefrigSysNum).Name,
                                           Subcooler(SubcoolerNum).Name));
                    ErrorsFound = true;
                }
            } // error check
        } // numsubcoolers

        for (RefrigSysNum = 1; RefrigSysNum <= state.dataRefrigCase->NumRefrigSystems; ++RefrigSysNum) {
            for (int SubcoolerNum = 1; SubcoolerNum <= state.dataRefrigCase->NumSimulationSubcoolers; ++SubcoolerNum) {
                if (Subcooler(SubcoolerNum).subcoolerType == SubcoolerType::LiquidSuction) {
                    continue;
                }
                if (Subcooler(SubcoolerNum).MechSourceSysID == RefrigSysNum) {
                    ++System(RefrigSysNum).NumMechSCServed;
                }
            }
            if (System(RefrigSysNum).NumMechSCServed > 0) {
                if (!allocated(System(RefrigSysNum).MechSCLoad)) {
                    System(RefrigSysNum).MechSCLoad.allocate(state.dataRefrigCase->NumSimulationSubcoolers);
                }
            }
        }
    } // NumSimulationSubcoolers > 0

    // **********  READ TRANSCRITICAL REFRIGERATION SYSTEMS  **********

    if (state.dataRefrigCase->NumTransRefrigSystems > 0) {
        CurrentModuleObject = "Refrigeration:TranscriticalSystem";
        for (int TransRefrigSysNum = 1; TransRefrigSysNum <= state.dataRefrigCase->NumTransRefrigSystems; ++TransRefrigSysNum) {
            state.dataInputProcessing->inputProcessor->getObjectItem(state,
                                                                     CurrentModuleObject,
                                                                     TransRefrigSysNum,
                                                                     Alphas,
                                                                     NumAlphas,
                                                                     Numbers,
                                                                     NumNumbers,
                                                                     IOStatus,
                                                                     lNumericBlanks,
                                                                     lAlphaBlanks,
                                                                     cAlphaFieldNames,
                                                                     cNumericFieldNames);

            ErrorObjectHeader eoh{routineName, CurrentModuleObject, Alphas(1)};

            Util::IsNameEmpty(state, Alphas(1), CurrentModuleObject, ErrorsFound);

            TransSystem(TransRefrigSysNum).Name = Alphas(1);

            // Read refrigerant for this system
            AlphaNum = 8;
            TransSystem(TransRefrigSysNum).RefrigerantName = Alphas(AlphaNum);
            if (TransSystem(TransRefrigSysNum).RefrigerantName.empty()) {
                ShowSevereEmptyField(state, eoh, Alphas(AlphaNum));
                ErrorsFound = true;
            } else if ((TransSystem(TransRefrigSysNum).refrig = Fluid::GetRefrig(state, TransSystem(TransRefrigSysNum).RefrigerantName)) == nullptr) {
                ShowSevereItemNotFound(state, eoh, cAlphaFieldNames(AlphaNum), Alphas(AlphaNum));
                ErrorsFound = true;
            }
            // error messages for refrigerants already found in fluidproperties

            // Read Transcritical System Type:  SingleStage or TwoStage
            if (lAlphaBlanks(2)) {
                ShowSevereEmptyField(state, eoh, cAlphaFieldNames(2));
                ErrorsFound = true;
            } else if ((TransSystem(TransRefrigSysNum).transSysType = static_cast<TransSysType>(getEnumValue(transSysTypeNamesUC, Alphas(2)))) ==
                       TransSysType::Invalid) {
                ShowSevereInvalidKey(state, eoh, cAlphaFieldNames(1), Alphas(2));
                ErrorsFound = true;
            } else if (TransSystem(TransRefrigSysNum).transSysType == TransSysType::SingleStage && lAlphaBlanks(3)) {
                // No medium temperature loads specified for a SingleStage system - display error
                ShowSevereEmptyField(state, eoh, cAlphaFieldNames(3), cAlphaFieldNames(2), Alphas(2));
                ErrorsFound = true;
            } else if (TransSystem(TransRefrigSysNum).transSysType == TransSysType::TwoStage && lAlphaBlanks(4)) {
                ShowSevereEmptyField(state, eoh, cAlphaFieldNames(3), cAlphaFieldNames(2), Alphas(2));
                ErrorsFound = true;
            }

            int NumCasesMT = 0;
            TransSystem(TransRefrigSysNum).NumCasesMT = 0;
            int NumCasesLT = 0;
            TransSystem(TransRefrigSysNum).NumCasesLT = 0;
            int NumWalkInsMT = 0;
            TransSystem(TransRefrigSysNum).NumWalkInsMT = 0;
            int NumWalkInsLT = 0;
            TransSystem(TransRefrigSysNum).NumWalkInsLT = 0;
            Real64 NominalTotalCaseCapMT = 0.0;
            Real64 NominalTotalCaseCapLT = 0.0;
            Real64 NominalTotalWalkInCapMT = 0.0;
            Real64 NominalTotalWalkInCapLT = 0.0;
            Real64 NominalTotalCoolingCap;
            TransSystem(TransRefrigSysNum).RefInventory = 0.0;

            //   Check for Medium Temperature Case or Walk-In or CaseAndWalkInList names
            AlphaNum = 3;

            if (!lAlphaBlanks(AlphaNum)) {

                // Entry for Alphas(AlphaNum) can be either a Case, WalkIn or CaseAndWalkInList name
                int CaseAndWalkInListNum = 0;
                int CaseNum = 0;
                int WalkInNum = 0;
                if (state.dataRefrigCase->NumSimulationCaseAndWalkInLists > 0) {
                    CaseAndWalkInListNum = Util::FindItemInList(Alphas(AlphaNum), CaseAndWalkInList);
                }
                if (state.dataRefrigCase->NumSimulationCases > 0) {
                    CaseNum = Util::FindItemInList(Alphas(AlphaNum), RefrigCase);
                }
                if (state.dataRefrigCase->NumSimulationWalkIns > 0) {
                    WalkInNum = Util::FindItemInList(Alphas(AlphaNum), WalkIn);
                }
                int NumNameMatches = 0;
                if (CaseAndWalkInListNum != 0) {
                    ++NumNameMatches;
                }
                if (CaseNum != 0) {
                    ++NumNameMatches;
                }
                if (WalkInNum != 0) {
                    ++NumNameMatches;
                }

                if (NumNameMatches != 1) { // name must uniquely point to a list or a single case or walkin or coil
                    ErrorsFound = true;
                    if (NumNameMatches == 0) {
                        ShowSevereError(state,
                                        format("{}{}=\"{}\", has an invalid {}: {}",
                                               RoutineName,
                                               CurrentModuleObject,
                                               TransSystem(TransRefrigSysNum).Name,
                                               cAlphaFieldNames(AlphaNum),
                                               Alphas(AlphaNum)));
                    } else if (NumNameMatches > 1) {
                        ShowSevereError(state,
                                        format("{}{}=\"{}\",  has a non-unique name that could be either a {}: {}",
                                               RoutineName,
                                               CurrentModuleObject,
                                               TransSystem(TransRefrigSysNum).Name,
                                               cAlphaFieldNames(AlphaNum),
                                               Alphas(AlphaNum)));
                    } // num matches = 0 or > 1
                } else if (CaseAndWalkInListNum != 0) { // Name points to a CaseAndWalkInList
                    NumCasesMT = CaseAndWalkInList(CaseAndWalkInListNum).NumCases;
                    NumWalkInsMT = CaseAndWalkInList(CaseAndWalkInListNum).NumWalkIns;
                    TransSystem(TransRefrigSysNum).NumCasesMT = NumCasesMT;
                    TransSystem(TransRefrigSysNum).NumWalkInsMT = NumWalkInsMT;
                    if (NumCasesMT > 0) {
                        if (!allocated(TransSystem(TransRefrigSysNum).CaseNumMT)) {
                            TransSystem(TransRefrigSysNum).CaseNumMT.allocate(NumCasesMT);
                        }
                        TransSystem(TransRefrigSysNum).CaseNumMT({1, NumCasesMT}) =
                            CaseAndWalkInList(CaseAndWalkInListNum).CaseItemNum({1, NumCasesMT});
                    }
                    if (NumWalkInsMT > 0) {
                        if (!allocated(TransSystem(TransRefrigSysNum).WalkInNumMT)) {
                            TransSystem(TransRefrigSysNum).WalkInNumMT.allocate(NumWalkInsMT);
                        }
                        TransSystem(TransRefrigSysNum).WalkInNumMT({1, NumWalkInsMT}) =
                            CaseAndWalkInList(CaseAndWalkInListNum).WalkInItemNum({1, NumWalkInsMT});
                    }
                } else if (CaseNum != 0) { // Name points to a case
                    NumCasesMT = 1;
                    TransSystem(TransRefrigSysNum).NumCasesMT = 1;
                    if (!allocated(TransSystem(TransRefrigSysNum).CaseNumMT)) {
                        TransSystem(TransRefrigSysNum).CaseNumMT.allocate(NumCasesMT);
                    }
                    TransSystem(TransRefrigSysNum).CaseNumMT(NumCases) = CaseNum;
                } else if (WalkInNum != 0) { // Name points to a walkin
                    NumWalkInsMT = 1;
                    TransSystem(TransRefrigSysNum).NumWalkInsMT = 1;
                    if (!allocated(TransSystem(TransRefrigSysNum).WalkInNumMT)) {
                        TransSystem(TransRefrigSysNum).WalkInNumMT.allocate(NumWalkInsMT);
                    }
                    TransSystem(TransRefrigSysNum).WalkInNumMT(NumWalkIns) = WalkInNum;
                } // NumNameMatches /= 1
            } // blank input for cases, walkins, or caseandwalkinlist

            if (NumCasesMT > 0) {
                // Find lowest design evap T
                // Sum rated capacity of all MT cases on system
                for (int caseIndex = 1; caseIndex <= NumCasesMT; ++caseIndex) {
                    // mark all cases on system as used by this system - checking for unused or non-unique cases
                    int CaseNum = TransSystem(TransRefrigSysNum).CaseNumMT(caseIndex);
                    ++RefrigCase(CaseNum).NumSysAttach;
                    NominalTotalCaseCapMT += RefrigCase(CaseNum).DesignRatedCap;
                    TransSystem(TransRefrigSysNum).RefInventory += RefrigCase(CaseNum).DesignRefrigInventory;
                    if (caseIndex == 1) { // look for lowest case design evap T for system
                        TransSystem(TransRefrigSysNum).TEvapDesignMT = RefrigCase(CaseNum).EvapTempDesign;
                    } else {
                        TransSystem(TransRefrigSysNum).TEvapDesignMT =
                            min(RefrigCase(CaseNum).EvapTempDesign, TransSystem(TransRefrigSysNum).TEvapDesignMT);
                    }
                } // CaseIndex=1,NumCases
            } // NumcasesMT > 0

            if (NumWalkInsMT > 0) {
                for (int WalkInIndex = 1; WalkInIndex <= NumWalkInsMT; ++WalkInIndex) {
                    int WalkInID = TransSystem(TransRefrigSysNum).WalkInNumMT(WalkInIndex);
                    // mark all WalkIns on rack as used by this system (checking for unused or non-unique WalkIns)
                    ++WalkIn(WalkInID).NumSysAttach;
                    NominalTotalWalkInCapMT += WalkIn(WalkInID).DesignRatedCap;
                    TransSystem(TransRefrigSysNum).RefInventory += WalkIn(WalkInID).DesignRefrigInventory;
                    // Defrost capacity is treated differently by compressor racks and detailed systems,
                    //  so this value may be adjusted (or warnings issued) after the walkin is assigned
                    //  to either the rack or system.
                    // for walkins served by detailed system, need capacity for both fluid and electric types.
                    if (WalkIn(WalkInID).DefrostCapacity <= -98.0) {
                        // - 99 used as a flag for blank input error message for detailed systems
                        ShowSevereError(state,
                                        format("{}Refrigeration:WalkIn=\"{}\", Defrost capacity must be greater than or equal to 0 W for "
                                               "electric and hotfluid defrost types",
                                               RoutineName,
                                               WalkIn(WalkInID).Name));
                        ErrorsFound = true;
                    }
                    // Find design evaporating temperature for system by getting min design evap for ALL loads
                    if ((WalkInIndex == 1) && (TransSystem(TransRefrigSysNum).NumCasesMT == 0)) {
                        // note use walk in index, not walkinid here to get
                        // first walkin on this suction group/system
                        TransSystem(TransRefrigSysNum).TEvapDesignMT = WalkIn(WalkInID).TEvapDesign;
                    } else {
                        TransSystem(TransRefrigSysNum).TEvapDesignMT =
                            min(WalkIn(WalkInID).TEvapDesign, TransSystem(TransRefrigSysNum).TEvapDesignMT);
                    }
                } // WalkInIndex=1,NumWalkIns
            } // NumWalkInsMT > 0

            //   Check for Low Temperature Case or Walk-In or CaseAndWalkInList names
            AlphaNum = 4;
            if (!lAlphaBlanks(AlphaNum)) {

                // Entry for Alphas(AlphaNum) can be either a Case, WalkIn or CaseAndWalkInList name
                int CaseAndWalkInListNum = 0;
                int CaseNum = 0;
                int WalkInNum = 0;
                if (state.dataRefrigCase->NumSimulationCaseAndWalkInLists > 0) {
                    CaseAndWalkInListNum = Util::FindItemInList(Alphas(AlphaNum), CaseAndWalkInList);
                }
                if (state.dataRefrigCase->NumSimulationCases > 0) {
                    CaseNum = Util::FindItemInList(Alphas(AlphaNum), RefrigCase);
                }
                if (state.dataRefrigCase->NumSimulationWalkIns > 0) {
                    WalkInNum = Util::FindItemInList(Alphas(AlphaNum), WalkIn);
                }
                int NumNameMatches = 0;
                if (CaseAndWalkInListNum != 0) {
                    ++NumNameMatches;
                }
                if (CaseNum != 0) {
                    ++NumNameMatches;
                }
                if (WalkInNum != 0) {
                    ++NumNameMatches;
                }

                if (NumNameMatches != 1) { // name must uniquely point to a list or a single case or walkin or coil
                    ErrorsFound = true;
                    if (NumNameMatches == 0) {
                        ShowSevereError(state,
                                        format("{}{}=\"{}\", has an invalid {}: {}",
                                               RoutineName,
                                               CurrentModuleObject,
                                               TransSystem(TransRefrigSysNum).Name,
                                               cAlphaFieldNames(AlphaNum),
                                               Alphas(AlphaNum)));
                    } else if (NumNameMatches > 1) {
                        ShowSevereError(state,
                                        format("{}{}=\"{}\",  has a non-unique name that could be either a {}: {}",
                                               RoutineName,
                                               CurrentModuleObject,
                                               TransSystem(TransRefrigSysNum).Name,
                                               cAlphaFieldNames(AlphaNum),
                                               Alphas(AlphaNum)));
                    } // num matches = 0 or > 1
                } else if (CaseAndWalkInListNum != 0) { // Name points to a CaseAndWalkInList
                    NumCasesLT = CaseAndWalkInList(CaseAndWalkInListNum).NumCases;
                    NumWalkInsLT = CaseAndWalkInList(CaseAndWalkInListNum).NumWalkIns;
                    TransSystem(TransRefrigSysNum).NumCasesLT = NumCasesLT;
                    TransSystem(TransRefrigSysNum).NumWalkInsLT = NumWalkInsLT;
                    if (NumCasesLT > 0) {
                        if (!allocated(TransSystem(TransRefrigSysNum).CaseNumLT)) {
                            TransSystem(TransRefrigSysNum).CaseNumLT.allocate(NumCasesLT);
                        }
                        TransSystem(TransRefrigSysNum).CaseNumLT({1, NumCasesLT}) =
                            CaseAndWalkInList(CaseAndWalkInListNum).CaseItemNum({1, NumCasesLT});
                    }
                    if (NumWalkInsLT > 0) {
                        if (!allocated(TransSystem(TransRefrigSysNum).WalkInNumLT)) {
                            TransSystem(TransRefrigSysNum).WalkInNumLT.allocate(NumWalkInsLT);
                        }
                        TransSystem(TransRefrigSysNum).WalkInNumLT({1, NumWalkInsLT}) =
                            CaseAndWalkInList(CaseAndWalkInListNum).WalkInItemNum({1, NumWalkInsLT});
                    }
                } else if (CaseNum != 0) { // Name points to a case
                    NumCasesLT = 1;
                    TransSystem(TransRefrigSysNum).NumCasesLT = 1;
                    if (!allocated(TransSystem(TransRefrigSysNum).CaseNumLT)) {
                        TransSystem(TransRefrigSysNum).CaseNumLT.allocate(NumCasesLT);
                    }
                    TransSystem(TransRefrigSysNum).CaseNumLT(NumCases) = CaseNum;
                } else if (WalkInNum != 0) { // Name points to a walkin
                    NumWalkInsLT = 1;
                    TransSystem(TransRefrigSysNum).NumWalkInsLT = 1;
                    if (!allocated(TransSystem(TransRefrigSysNum).WalkInNumLT)) {
                        TransSystem(TransRefrigSysNum).WalkInNumLT.allocate(NumWalkInsLT);
                    }
                    TransSystem(TransRefrigSysNum).WalkInNumLT(NumWalkIns) = WalkInNum;
                } // NumNameMatches /= 1
            } // blank input for cases, walkins, or caseandwalkinlist

            if (NumCasesLT > 0) {
                // Find lowest design evap T
                // Sum rated capacity of all LT cases on system
                for (int caseIndex = 1; caseIndex <= NumCasesLT; ++caseIndex) {
                    // mark all cases on system as used by this system - checking for unused or non-unique cases
                    int CaseNum = TransSystem(TransRefrigSysNum).CaseNumLT(caseIndex);
                    ++RefrigCase(CaseNum).NumSysAttach;
                    NominalTotalCaseCapLT += RefrigCase(CaseNum).DesignRatedCap;
                    TransSystem(TransRefrigSysNum).RefInventory += RefrigCase(CaseNum).DesignRefrigInventory;
                    if (caseIndex == 1) { // look for lowest case design evap T for system
                        TransSystem(TransRefrigSysNum).TEvapDesignLT = RefrigCase(CaseNum).EvapTempDesign;
                    } else {
                        TransSystem(TransRefrigSysNum).TEvapDesignLT =
                            min(RefrigCase(CaseNum).EvapTempDesign, TransSystem(TransRefrigSysNum).TEvapDesignLT);
                    }
                } // CaseIndex=1,NumCases
            } // NumcasesLT > 0

            if (NumWalkInsLT > 0) {
                for (int WalkInIndex = 1; WalkInIndex <= NumWalkInsLT; ++WalkInIndex) {
                    int WalkInID = TransSystem(TransRefrigSysNum).WalkInNumLT(WalkInIndex);
                    // mark all WalkIns on rack as used by this system (checking for unused or non-unique WalkIns)
                    ++WalkIn(WalkInID).NumSysAttach;
                    NominalTotalWalkInCapLT += WalkIn(WalkInID).DesignRatedCap;
                    TransSystem(TransRefrigSysNum).RefInventory += WalkIn(WalkInID).DesignRefrigInventory;
                    // Defrost capacity is treated differently by compressor racks and detailed systems,
                    //  so this value may be adjusted (or warnings issued) after the walkin is assigned
                    //  to either the rack or system.
                    // for walkins served by detailed system, need capacity for both fluid and electric types.
                    if (WalkIn(WalkInID).DefrostCapacity <= -98.0) {
                        // - 99 used as a flag for blank input error message for detailed systems
                        ShowSevereError(state,
                                        format("{}Refrigeration:WalkIn=\"{}\", Defrost capacity must be greater than or equal to 0 W for "
                                               "electric and hotfluid defrost types",
                                               RoutineName,
                                               WalkIn(WalkInID).Name));
                        ErrorsFound = true;
                    }
                    // Find design evaporating temperature for system by getting min design evap for ALL loads
                    if ((WalkInIndex == 1) && (TransSystem(TransRefrigSysNum).NumCasesLT == 0)) {
                        // note use walk in index, not walkinid here to get
                        // first walkin on this suction group/system
                        TransSystem(TransRefrigSysNum).TEvapDesignLT = WalkIn(WalkInID).TEvapDesign;
                    } else {
                        TransSystem(TransRefrigSysNum).TEvapDesignLT =
                            min(WalkIn(WalkInID).TEvapDesign, TransSystem(TransRefrigSysNum).TEvapDesignLT);
                    }
                } // WalkInIndex=1,NumWalkIns
            } // NumWalkInsMT > 0

            NominalTotalCoolingCap = NominalTotalCaseCapMT + NominalTotalCaseCapLT + NominalTotalWalkInCapMT + NominalTotalWalkInCapLT;

            // Read Gas Cooler
            // currently assumes one gas cooler per refrigeration system and but multiple systems allowed per gas cooler
            AlphaNum = 5;
            int NumGasCoolers = 1;
            if (!allocated(TransSystem(TransRefrigSysNum).GasCoolerNum)) {
                TransSystem(TransRefrigSysNum).GasCoolerNum.allocate(NumGasCoolers);
            }
            TransSystem(TransRefrigSysNum).NumGasCoolers = 1;
            // Find gascooler number
            int GCNum = Util::FindItemInList(Alphas(AlphaNum), GasCooler);

            if (GCNum == 0) { //  Invalid Gas Cooler attached to Transcritical Refrigeration System
                ShowSevereError(state,
                                format(R"({}{}="{}", has an invalid {} defined as "{}".)",
                                       RoutineName,
                                       CurrentModuleObject,
                                       TransSystem(TransRefrigSysNum).Name,
                                       cAlphaFieldNames(AlphaNum),
                                       Alphas(AlphaNum)));
                ErrorsFound = true;
            } else if (GCNum != 0) { //  Gas Cooler attached to Transcritical Refrigeration System
                TransSystem(TransRefrigSysNum).GasCoolerNum(NumGasCoolers) = GCNum;
                TransSystem(TransRefrigSysNum).NumGasCoolers = 1;
                // Now take care of case where multiple systems share a gas cooler
                ++GasCooler(GCNum).NumSysAttach;
                GasCooler(GCNum).SysNum(GasCooler(GCNum).NumSysAttach) = TransRefrigSysNum;
                TransSystem(TransRefrigSysNum).RefInventory +=
                    GasCooler(GCNum).RefReceiverInventory + GasCooler(GCNum).RefPipingInventory + GasCooler(GCNum).RefOpCharge;
                if (GasCooler(GCNum).GasCoolerRejectHeatToZone) {
                    TransSystem(TransRefrigSysNum).SystemRejectHeatToZone = true;
                }
            }

            // Read High Pressure Compressor
            AlphaNum = 6;
            int NumCompressorsSys = 0;
            if (lAlphaBlanks(AlphaNum)) {
                // blank input where must have compressor or compressor list input.
                ShowSevereError(state, format("{}{} {}\" : must be input.", RoutineName, CurrentModuleObject, cAlphaFieldNames(AlphaNum)));
                ErrorsFound = true;
            } else { //     Entry for Alphas(AlphaNum) can be either a compressor name or a compressorlist name
                int ListNum = Util::FindItemInList(Alphas(AlphaNum), CompressorLists);
                int CompNum = Util::FindItemInList(Alphas(AlphaNum), Compressor);
                if ((ListNum == 0) && (CompNum == 0)) { // name doesn't match either a compressor or a compressor list
                    ShowSevereError(state,
                                    format(R"({}{}, "{}", has an invalid or undefined value="{}".)",
                                           RoutineName,
                                           CurrentModuleObject,
                                           cAlphaFieldNames(AlphaNum),
                                           Alphas(AlphaNum)));
                    ErrorsFound = true;
                } else if ((ListNum != 0) && (CompNum != 0)) { // have compressor list and compressor with same name
                    ShowSevereError(state,
                                    format("{}{} {}, has a non-unique name used for both Compressor and CompressorList name: \"{}\".",
                                           RoutineName,
                                           CurrentModuleObject,
                                           cAlphaFieldNames(AlphaNum),
                                           Alphas(AlphaNum)));
                    ErrorsFound = true;
                } else if (ListNum != 0) {
                    NumCompressorsSys = CompressorLists(ListNum).NumCompressors;
                    TransSystem(TransRefrigSysNum).NumCompressorsHP = NumCompressorsSys;
                    if (!allocated(TransSystem(TransRefrigSysNum).CompressorNumHP)) {
                        TransSystem(TransRefrigSysNum).CompressorNumHP.allocate(NumCompressorsSys);
                    }
                    TransSystem(TransRefrigSysNum).CompressorNumHP({1, NumCompressorsSys}) =
                        CompressorLists(ListNum).CompItemNum({1, NumCompressorsSys});
                } else if (CompNum != 0) {
                    NumCompressorsSys = 1;
                    TransSystem(TransRefrigSysNum).NumCompressorsHP = 1;
                    if (!allocated(TransSystem(TransRefrigSysNum).CompressorNumHP)) {
                        TransSystem(TransRefrigSysNum).CompressorNumHP.allocate(NumCompressorsSys);
                    }
                    TransSystem(TransRefrigSysNum).CompressorNumHP(NumCompressorsSys) = CompNum;
                }
                // Sum rated capacity of all HP compressors on system
                NominalTotalCompCapHP = 0.0;
                for (int CompIndex = 1; CompIndex <= NumCompressorsSys; ++CompIndex) {
                    CompNum = TransSystem(TransRefrigSysNum).CompressorNumHP(CompIndex);

                    if (Compressor(CompNum).TransFlag) { //  Calculate nominal capacity of transcritical Compressor
                        Real64 GCOutletH = TransSystem(TransRefrigSysNum)
                                               .refrig->getSupHeatEnthalpy(state,
                                                                           GasCooler(TransSystem(TransRefrigSysNum).GasCoolerNum(1)).RatedOutletT,
                                                                           GasCooler(TransSystem(TransRefrigSysNum).GasCoolerNum(1)).RatedOutletP,
                                                                           routineName);
                        Compressor(CompNum).NomCap = Curve::CurveValue(
                            state, Compressor(CompNum).TransCapacityCurvePtr, TransSystem(TransRefrigSysNum).TEvapDesignMT, GCOutletH);
                        NominalTotalCompCapHP += Compressor(CompNum).NomCap;
                        ++Compressor(CompNum).NumSysAttach;
                    } else { //  Subcritical compressor attached to transcritical system - show error
                        ShowSevereError(
                            state,
                            format("{}{}, No transcritical CO2 compressors are attached to the transcritical refrigeration system, \"{}\".",
                                   RoutineName,
                                   CurrentModuleObject,
                                   TransSystem(TransRefrigSysNum).Name));
                        ErrorsFound = true;
                    }
                }
            }

            // Read Low Pressure Compressor
            AlphaNum = 7;
            NumCompressorsSys = 0;

            if ((lAlphaBlanks(AlphaNum)) && (TransSystem(TransRefrigSysNum).transSysType == TransSysType::TwoStage)) {
                // TwoStage system type is specified but low pressure compressor input is blank
                ShowSevereError(state,
                                format("{}{}, The transcritical refrigeration system, \"{}\", is specified to be \"TwoStage\", "
                                       "however, the \"{}\" is not given.",
                                       RoutineName,
                                       CurrentModuleObject,
                                       TransSystem(TransRefrigSysNum).Name,
                                       cAlphaFieldNames(AlphaNum)));
                ErrorsFound = true;
            } else if ((!(lAlphaBlanks(AlphaNum))) && (TransSystem(TransRefrigSysNum).transSysType == TransSysType::SingleStage)) {
                // SingleStage system type with low pressure compressors specified. Ignore low pressure compressors
                ShowWarningError(state,
                                 format("{}{}, The transcritical refrigeration system, \"{}\", is specified to be \"SingleStage\", "
                                        "however, a \"{}\" was found.  The low pressure compressors will be ignored and will not simulated.",
                                        RoutineName,
                                        CurrentModuleObject,
                                        TransSystem(TransRefrigSysNum).Name,
                                        cAlphaFieldNames(AlphaNum)));
            } else if ((!(lAlphaBlanks(AlphaNum))) && (TransSystem(TransRefrigSysNum).transSysType == TransSysType::TwoStage)) {
                // TwoStage system with low pressure compressors specified
                int ListNum = Util::FindItemInList(Alphas(AlphaNum), CompressorLists);
                int CompNum = Util::FindItemInList(Alphas(AlphaNum), Compressor);
                if ((ListNum == 0) && (CompNum == 0)) { // name doesn't match either a compressor or a compressor list
                    ShowSevereError(state,
                                    format(R"({}{}, "{}", has an invalid or undefined value="{}".)",
                                           RoutineName,
                                           CurrentModuleObject,
                                           cAlphaFieldNames(AlphaNum),
                                           Alphas(AlphaNum)));
                    ErrorsFound = true;
                } else if ((ListNum != 0) && (CompNum != 0)) { // have compressor list and compressor with same name
                    ShowSevereError(state,
                                    format("{}{} {}, has a non-unique name used for both Compressor and CompressorList name: \"{}\".",
                                           RoutineName,
                                           CurrentModuleObject,
                                           cAlphaFieldNames(AlphaNum),
                                           Alphas(AlphaNum)));
                    ErrorsFound = true;
                } else if (ListNum != 0) {
                    NumCompressorsSys = CompressorLists(ListNum).NumCompressors;
                    TransSystem(TransRefrigSysNum).NumCompressorsLP = NumCompressorsSys;
                    if (!allocated(TransSystem(TransRefrigSysNum).CompressorNumLP)) {
                        TransSystem(TransRefrigSysNum).CompressorNumLP.allocate(NumCompressorsSys);
                    }
                    TransSystem(TransRefrigSysNum).CompressorNumLP({1, NumCompressorsSys}) =
                        CompressorLists(ListNum).CompItemNum({1, NumCompressorsSys});
                } else if (CompNum != 0) {
                    NumCompressorsSys = 1;
                    TransSystem(TransRefrigSysNum).NumCompressorsLP = 1;
                    if (!allocated(TransSystem(TransRefrigSysNum).CompressorNumLP)) {
                        TransSystem(TransRefrigSysNum).CompressorNumLP.allocate(NumCompressorsSys);
                    }
                    TransSystem(TransRefrigSysNum).CompressorNumLP(NumCompressorsSys) = CompNum;
                }
                // Sum rated capacity of all LP compressors on system
                NominalTotalCompCapLP = 0.0;
                for (int CompIndex = 1; CompIndex <= NumCompressorsSys; ++CompIndex) {
                    CompNum = TransSystem(TransRefrigSysNum).CompressorNumLP(CompIndex);
                    if (TransSystem(TransRefrigSysNum).transSysType == TransSysType::TwoStage) { //  Calculate capacity of LP compressors
                        Compressor(CompNum).NomCap = Curve::CurveValue(state,
                                                                       Compressor(CompNum).CapacityCurvePtr,
                                                                       TransSystem(TransRefrigSysNum).TEvapDesignLT,
                                                                       TransSystem(TransRefrigSysNum).TEvapDesignMT);
                        NominalTotalCompCapLP += Compressor(CompNum).NomCap;
                        ++Compressor(CompNum).NumSysAttach;
                    }
                }
            }

            // Read Receiver Pressure
            if (!lNumericBlanks(1)) {
                TransSystem(TransRefrigSysNum).PReceiver = Numbers(1);
            } else { // Default value receiver pressure = 4000000 Pa
                TransSystem(TransRefrigSysNum).PReceiver = 4.0e6;
            }

            // Check receiver temperature against minimum condensing temperature (from gas cooler input) and design evaporator temperatures
            TransSystem(TransRefrigSysNum).TReceiver =
                TransSystem(TransRefrigSysNum).refrig->getSatTemperature(state, TransSystem(TransRefrigSysNum).PReceiver, routineName);
            if (TransSystem(TransRefrigSysNum).TReceiver > GasCooler(TransSystem(TransRefrigSysNum).GasCoolerNum(NumGasCoolers)).MinCondTemp) {
                ShowWarningError(state,
                                 format("{}{}=\"{}: The receiver temperature ({:.2R}C) is greater than the minimum condensing temperature "
                                        "specified for subcritical operation ({:.2R}C).",
                                        RoutineName,
                                        CurrentModuleObject,
                                        TransSystem(TransRefrigSysNum).Name,
                                        TransSystem(TransRefrigSysNum).TReceiver,
                                        GasCooler(TransSystem(TransRefrigSysNum).GasCoolerNum(NumGasCoolers)).MinCondTemp));
                ShowContinueError(state, "  The minimum condensing temperature will be set at 5C greater than the receiver temperature.");
                GasCooler(TransSystem(TransRefrigSysNum).GasCoolerNum(NumGasCoolers)).MinCondTemp = TransSystem(TransRefrigSysNum).TReceiver + 5.0;
            }
            if (NominalTotalCompCapLP > 0.0) {
                if (TransSystem(TransRefrigSysNum).TReceiver <= TransSystem(TransRefrigSysNum).TEvapDesignLT) {
                    ShowSevereError(state,
                                    format("{}{}=\"{}: The receiver temperature ({:.2R}C) is less than the design evaporator temperature for the "
                                           "low temperature loads ({:.2R}C).",
                                           RoutineName,
                                           CurrentModuleObject,
                                           TransSystem(TransRefrigSysNum).Name,
                                           TransSystem(TransRefrigSysNum).TReceiver,
                                           TransSystem(TransRefrigSysNum).TEvapDesignLT));
                    ShowContinueError(state,
                                      "  Ensure that the receiver temperature is sufficiently greater than the design evaporator temperature for "
                                      "the low temperature loads.");
                    ShowContinueError(state,
                                      "  A receiver pressure between 3.0 MPa to 4.0 MPa will typically result in an adequate receiver temperature.");
                    ErrorsFound = true;
                }
            }
            if (NominalTotalCompCapHP > 0.0) {
                if (TransSystem(TransRefrigSysNum).TReceiver <= TransSystem(TransRefrigSysNum).TEvapDesignMT) {
                    ShowSevereError(state,
                                    format("{}{}=\"{}: The receiver temperature ({:.2R}C) is less than the design evaporator temperature for the "
                                           "medium temperature loads ({:.2R}C).",
                                           RoutineName,
                                           CurrentModuleObject,
                                           TransSystem(TransRefrigSysNum).Name,
                                           TransSystem(TransRefrigSysNum).TReceiver,
                                           TransSystem(TransRefrigSysNum).TEvapDesignMT));
                    ShowContinueError(state,
                                      "  Ensure that the receiver temperature is sufficiently greater than the design evaporator temperature for "
                                      "the medium temperature loads.");
                    ShowContinueError(state,
                                      "  A receiver pressure between 3.0 MPa to 4.0 MPa will typically result in an adequate receiver temperature.");
                    ErrorsFound = true;
                }
            }

            // Read subcooler effectiveness
            if (!lNumericBlanks(2)) {
                TransSystem(TransRefrigSysNum).SCEffectiveness = Numbers(2);
            } else { // Default value effectiveness = 0.4
                TransSystem(TransRefrigSysNum).PReceiver = 0.4;
            }
            // Check subcooler effectiveness value, must be value between 0 and 1
            if ((TransSystem(TransRefrigSysNum).SCEffectiveness < 0) || (TransSystem(TransRefrigSysNum).SCEffectiveness > 1)) {
                ShowSevereError(state,
                                format("{}{}=\"{}: The value for subcooler effectiveness is invalid.  The subcooler effectiveness must be a value "
                                       "greater than or equal to zero and less than or equal to one.",
                                       RoutineName,
                                       CurrentModuleObject,
                                       TransSystem(TransRefrigSysNum).Name));
                ErrorsFound = true;
            }

            // Suction piping heat gain - optional
            //  Input UA and identify the Zone containing the bulk of the suction piping
            //  This Zone ID will be used to determine the temperature used for suction piping heat gain.
            //  The pipe heat gains are also counted as cooling credit for the zone.
            //  Zone Id is only required if Sum UA Suction Piping >0.0
            //  Get the Zone and zone node numbers from the zone name entered by the user
            AlphaNum = 9; // Medium temperature suction piping
            TransSystem(TransRefrigSysNum).SumUASuctionPipingMT = 0.0;
            if (!lNumericBlanks(3) && !lAlphaBlanks(AlphaNum)) {
                TransSystem(TransRefrigSysNum).SumUASuctionPipingMT = Numbers(3);
                TransSystem(TransRefrigSysNum).SuctionPipeActualZoneNumMT = Util::FindItemInList(Alphas(AlphaNum), state.dataHeatBal->Zone);
                TransSystem(TransRefrigSysNum).SuctionPipeZoneNodeNumMT =
                    DataZoneEquipment::GetSystemNodeNumberForZone(state, TransSystem(TransRefrigSysNum).SuctionPipeActualZoneNumMT);
                if (TransSystem(TransRefrigSysNum).SuctionPipeZoneNodeNumMT == 0) {
                    ShowSevereError(state,
                                    format(R"({}{}="{}", System Node Number not found for {} = "{}" even though {} is greater than zero.)",
                                           RoutineName,
                                           CurrentModuleObject,
                                           TransSystem(TransRefrigSysNum).Name,
                                           cAlphaFieldNames(AlphaNum),
                                           Alphas(AlphaNum),
                                           cNumericFieldNames(3)));
                    ShowContinueError(state,
                                      "  The medium temperature suction piping heat gain cannot be calculated unless a Zone is defined to "
                                      "determine the environmental temperature surrounding the piping.");
                    ErrorsFound = true;
                } else {
                    state.dataRefrigCase->RefrigPresentInZone(TransSystem(TransRefrigSysNum).SuctionPipeActualZoneNumMT) = true;
                }
            } else if (!lNumericBlanks(3) && lAlphaBlanks(AlphaNum)) {
                ShowWarningError(state,
                                 format("{}{}=\"{}\" {} not found even though {} is greater than zero.",
                                        RoutineName,
                                        CurrentModuleObject,
                                        TransSystem(TransRefrigSysNum).Name,
                                        cAlphaFieldNames(AlphaNum),
                                        cNumericFieldNames(3)));
                ShowContinueError(state,
                                  "  The medium temperature suction piping heat gain will not be calculated unless a Zone is defined to "
                                  "determine the environmental temperature surrounding the piping.");
            } else if (lNumericBlanks(3) && !lAlphaBlanks(AlphaNum)) {
                ShowWarningError(state,
                                 format("{}{}=\"{}\" {} will not be used and suction piping heat gain will not be calculated because {} was blank.",
                                        RoutineName,
                                        CurrentModuleObject,
                                        TransSystem(TransRefrigSysNum).Name,
                                        cAlphaFieldNames(AlphaNum),
                                        cNumericFieldNames(3)));
            } // Medium temperature suction piping heat gains

            AlphaNum = 10; // Low temperature suction piping
            TransSystem(TransRefrigSysNum).SumUASuctionPipingLT = 0.0;
            if (!lNumericBlanks(4) && !lAlphaBlanks(AlphaNum)) {
                TransSystem(TransRefrigSysNum).SumUASuctionPipingLT = Numbers(4);
                TransSystem(TransRefrigSysNum).SuctionPipeActualZoneNumLT = Util::FindItemInList(Alphas(AlphaNum), state.dataHeatBal->Zone);
                TransSystem(TransRefrigSysNum).SuctionPipeZoneNodeNumLT =
                    DataZoneEquipment::GetSystemNodeNumberForZone(state, TransSystem(TransRefrigSysNum).SuctionPipeActualZoneNumLT);
                if (TransSystem(TransRefrigSysNum).SuctionPipeZoneNodeNumLT == 0) {
                    ShowSevereError(state,
                                    format(R"({}{}="{}", System Node Number not found for {} = "{}" even though {} is greater than zero.)",
                                           RoutineName,
                                           CurrentModuleObject,
                                           TransSystem(TransRefrigSysNum).Name,
                                           cAlphaFieldNames(AlphaNum),
                                           Alphas(AlphaNum),
                                           cNumericFieldNames(4)));
                    ShowContinueError(state,
                                      "  The low temperature suction piping heat gain cannot be calculated unless a Zone is defined to "
                                      "determine the environmental temperature surrounding the piping.");
                    ErrorsFound = true;
                } else {
                    state.dataRefrigCase->RefrigPresentInZone(TransSystem(TransRefrigSysNum).SuctionPipeActualZoneNumLT) = true;
                }
            } else if (!lNumericBlanks(4) && lAlphaBlanks(AlphaNum)) {
                ShowWarningError(state,
                                 format("{}{}=\"{}\" {} not found even though {} is greater than zero.",
                                        RoutineName,
                                        CurrentModuleObject,
                                        TransSystem(TransRefrigSysNum).Name,
                                        cAlphaFieldNames(AlphaNum),
                                        cNumericFieldNames(4)));
                ShowContinueError(state,
                                  "  The low temperature suction piping heat gain will not be calculated unless a Zone is defined to determine "
                                  "the environmental temperature surrounding the piping.");
            } else if (lNumericBlanks(4) && !lAlphaBlanks(AlphaNum)) {
                ShowWarningError(state,
                                 format("{}{}=\"{}\" {} will not be used and suction piping heat gain will not be calculated because {} was blank.",
                                        RoutineName,
                                        CurrentModuleObject,
                                        TransSystem(TransRefrigSysNum).Name,
                                        cAlphaFieldNames(AlphaNum),
                                        cNumericFieldNames(4)));
            } // Low temperature suction piping heat gains

            AlphaNum = 11;
            if (!lAlphaBlanks(AlphaNum)) {
                TransSystem(TransRefrigSysNum).EndUseSubcategory = Alphas(AlphaNum);
            }

            // Compare the rated capacity of compressor, condenser, and cases.
            // Note, rated capacities can be far off from operating capacities, but rough check.
            Real64 NominalCondCap = GasCooler(TransSystem(TransRefrigSysNum).GasCoolerNum(1)).RatedCapacity;
            Real64 NominalTotalCompCap = NominalTotalCompCapHP + NominalTotalCompCapLP;
            if ((NominalTotalCompCap < (0.7 * NominalTotalCoolingCap)) || (NominalCondCap < (1.3 * NominalTotalCoolingCap))) {
                ShowWarningError(
                    state, format("{}=\"{}\", You may wish to check the system sizing.", CurrentModuleObject, TransSystem(TransRefrigSysNum).Name));
                ShowContinueError(
                    state,
                    format("Total nominal cooling capacity is {:.0R}W. Condenser capacity is {:.0R}W. Nominal compressor capacity is {:.0R}W.",
                           NominalTotalCoolingCap,
                           NominalCondCap,
                           NominalTotalCompCap));
            }

        } // Transcritical refrigeration systems

    } //(NumTransRefrigSystems > 0)

    DayValues.deallocate();
    Alphas.deallocate();
    Numbers.deallocate();
    cAlphaFieldNames.deallocate();
    cNumericFieldNames.deallocate();
    lAlphaBlanks.deallocate();
    lNumericBlanks.deallocate();

    if (state.dataRefrigCase->NumSimulationCases > 0) {
        // Find unused and non-unique display case objects to report in eio and err file and sum
        //    all HVAC RA fractions and write error message if greater than 1 for any zone
        for (int ZoneIndex = 1; ZoneIndex <= state.dataGlobal->NumOfZones; ++ZoneIndex) { // numofzones from dataglobals
            Real64 TempRAFraction = CaseRAFraction(ZoneIndex).TotalCaseRAFraction;
            for (int CaseNum = 1; CaseNum <= state.dataRefrigCase->NumSimulationCases; ++CaseNum) {
                // TempRaFraction already includes contributions from ALL cases in zone
                // Want to delete portion from unused cases (numsysattach = 0)that will never be simulated
                if (RefrigCase(CaseNum).ActualZoneNum != ZoneIndex || RefrigCase(CaseNum).NumSysAttach > 0) {
                    continue;
                }
                TempRAFraction -= RefrigCase(CaseNum).RAFrac;
            } // NumSimulationCases
            if (TempRAFraction > 1.0) {
                ShowSevereError(
                    state,
                    format("{}: Refrigeration:Case, Refrigerated case return air fraction for all cases in zone=\"{}\" is greater than 1.0.",
                           RoutineName,
                           CaseRAFraction(ZoneIndex).ZoneName));
                // check in comment, can't use "currentModuleObject" because not in get input subroutine where that is known
                ErrorsFound = true;
            }
        } // ZoneIndex=1,DataGlobals::NumOfZones

        CaseRAFraction.deallocate(); // only used for input check just completed
        // check for cases not connected to systems and cases connected
        // more than once (twice in a system or to more than one system)

        state.dataRefrigCase->NumUnusedRefrigCases = 0;
        for (int CaseNum = 1; CaseNum <= state.dataRefrigCase->NumSimulationCases; ++CaseNum) {
            if (RefrigCase(CaseNum).NumSysAttach == 1) {
                continue;
            }
            if (RefrigCase(CaseNum).NumSysAttach < 1) {
                ++state.dataRefrigCase->NumUnusedRefrigCases;
                if (state.dataGlobal->DisplayExtraWarnings) {
                    //  individual case names listed if DataGlobals::DisplayExtraWarnings option selected
                    ShowWarningError(state, format("{}: Refrigeration:Case=\"{}\" unused. ", RoutineName, RefrigCase(CaseNum).Name));
                } // display extra warnings - give a list of unused cases
            } // unused case
            if (RefrigCase(CaseNum).NumSysAttach > 1) {
                ErrorsFound = true;
                ShowSevereError(
                    state, format("{}: Refrigeration:Case=\"{}\", Same refrigerated case name referenced ", RoutineName, RefrigCase(CaseNum).Name));
                ShowContinueError(state, " by more than one refrigeration system and/or compressor rack.");
            } // if looking for same case attached to multiple systems/racks
        } // NumSimulationCases

        if ((state.dataRefrigCase->NumUnusedRefrigCases > 0) && (!state.dataGlobal->DisplayExtraWarnings)) {
            //  write to error file,
            //  summary number of unused cases given if DataGlobals::DisplayExtraWarnings option not selected
            ShowWarningError(state,
                             format("Refrigeration:Case -> {} unused refrigerated case(s) found during input processing.",
                                    state.dataRefrigCase->NumUnusedRefrigCases));
            ShowContinueError(state, "  These refrigerated cases are in the input file but are not connected to a ");
            ShowContinueError(state, "  Refrigeration:CompressorRack, Refrigeration:System, or Refrigeration:SecondarySystem object.");
            ShowContinueError(state, "  These unused refrigeration cases will not be simulated.");
            ShowContinueError(state, "  Use Output:Diagnostics,DisplayUnusedObjects; to see them. ");
        } // NumUnusedRefrigCases
    } // numsimulation cases > 0

    if (state.dataRefrigCase->NumSimulationCompressors > 0) {
        // check for compressors not connected to systems and compressors connected more than once
        // (twice in a system or to more than one system)
        state.dataRefrigCase->NumUnusedCompressors = 0;
        for (int CompNum = 1; CompNum <= state.dataRefrigCase->NumSimulationCompressors; ++CompNum) {
            if (Compressor(CompNum).NumSysAttach == 1) {
                continue;
            }
            if (Compressor(CompNum).NumSysAttach < 1) {
                ++state.dataRefrigCase->NumUnusedCompressors;
                if (state.dataGlobal->DisplayExtraWarnings) {
                    //  individual compressor names listed if DataGlobals::DisplayExtraWarnings option selected
                    ShowWarningError(state, format("{}: Refrigeration:Compressor=\"{}\" unused. ", RoutineName, Compressor(CompNum).Name));
                } // display extra warnings - give a list of unused compressors
            } // unused compressor
            if (Compressor(CompNum).NumSysAttach > 1) {
                ErrorsFound = true;
                ShowSevereError(state,
                                format("{}: Refrigeration:Compressor=\"{}\", Same refrigeration compressor name referenced",
                                       RoutineName,
                                       Compressor(CompNum).Name));
                ShowContinueError(state, " by more than one refrigeration system.");
            } // looking for same compressor attached to multiple systems/racks
        } // NumSimulationCompressors

        if ((state.dataRefrigCase->NumUnusedCompressors > 0) && (!state.dataGlobal->DisplayExtraWarnings)) {
            //  write to error file,
            //  summary number of unused compressors given if DataGlobals::DisplayExtraWarnings option not selected
            ShowWarningError(state,
                             format("Refrigeration:Compressor -> {} unused refrigeration compressor(s) found during input processing.",
                                    state.dataRefrigCase->NumUnusedCompressors));
            ShowContinueError(state,
                              "  Those refrigeration compressors are in the input file but are not connected to a Refrigeration:System object.");
            ShowContinueError(state, "   These unused refrigeration compressors will not be simulated.");
            ShowContinueError(state, "   Use Output:Diagnostics,DisplayUnusedObjects; to see them. ");
        } // NumUnusedCompressors
    } // NumSimulationCompressors > 0

    int NumUnusedWalkIns = 0;
    if (state.dataRefrigCase->NumSimulationWalkIns > 0) {
        // check for refrigeration WalkIns not connected to any systems and
        //  refrigeration WalkIns connected more than once
        for (int WalkInNum = 1; WalkInNum <= state.dataRefrigCase->NumSimulationWalkIns; ++WalkInNum) {
            if (WalkIn(WalkInNum).NumSysAttach == 1) {
                continue;
            }
            if (WalkIn(WalkInNum).NumSysAttach < 1) {
                ++NumUnusedWalkIns;
                if (state.dataGlobal->DisplayExtraWarnings) {
                    //  individual walkin names listed if DataGlobals::DisplayExtraWarnings option selected
                    ShowWarningError(state, format("{}: Refrigeration:WalkIn=\"{}\" unused. ", RoutineName, WalkIn(WalkInNum).Name));
                } // display extra warnings - give a list of unused WalkIns
            } // unused walkin
            if (WalkIn(WalkInNum).NumSysAttach > 1) {
                ErrorsFound = true;
                ShowSevereError(
                    state, format("{}: Refrigeration:WalkIn=\"{}\", Same Refrigeration WalkIn name referenced", RoutineName, WalkIn(WalkInNum).Name));
                ShowContinueError(state, " by more than one refrigeration system and/or compressor rack.");
            } // if looking for same walk in attached to multiple systems/racks
        } // NumSimulationWalkIns

        if ((NumUnusedWalkIns > 0) && (!state.dataGlobal->DisplayExtraWarnings)) {
            //  write to error file,
            //  summary number of unused walkins given if DataGlobals::DisplayExtraWarnings option not selected
            ShowWarningError(
                state,
                format("{}Refrigeration:WalkIn -> {} unused refrigeration WalkIns found during input processing.", RoutineName, NumUnusedWalkIns));
            ShowContinueError(state, "   Those refrigeration WalkIns are in the input file but are not connected to a ");
            ShowContinueError(state, "   Refrigeration:CompressorRack, Refrigeration:System or Refrigeration:SecondarySystem object.");
            ShowContinueError(state, "   These unused refrigeration WalkIns will not be simulated.");
            ShowContinueError(state, "   Use Output:Diagnostics,DisplayUnusedObjects; to see them. ");
        } // NumUnusedWalkIns
    } // NumSimulationWalkIns > 0

    if (state.dataRefrigCase->NumSimulationRefrigAirChillers > 0) {
        // check for air chillers not connected to any systems and
        //  air chillers connected more than once
        state.dataRefrigCase->NumUnusedCoils = 0;
        for (int CoilNum = 1; CoilNum <= state.dataRefrigCase->NumSimulationRefrigAirChillers; ++CoilNum) {
            if (WarehouseCoil(CoilNum).NumSysAttach == 1) {
                continue;
            }
            if (WarehouseCoil(CoilNum).NumSysAttach < 1) {
                ++NumUnusedWalkIns;
                if (state.dataGlobal->DisplayExtraWarnings) {
                    //  individual walkin names listed if DataGlobals::DisplayExtraWarnings option selected
                    ShowWarningError(state, format("{}: Refrigeration:AirChiller=\"{}\" unused. ", RoutineName, WarehouseCoil(CoilNum).Name));
                } // display extra warnings - give a list of unused chillers
            } // unused chiller
            if (WarehouseCoil(CoilNum).NumSysAttach > 1) {
                ErrorsFound = true;
                ShowSevereError(state,
                                format("{}: Refrigeration:AirChiller=\"{}\", Same Refrigeration Air Chiller name referenced",
                                       RoutineName,
                                       WarehouseCoil(CoilNum).Name));
                ShowContinueError(state, " by more than one refrigeration system and/or compressor rack.");
            } // if looking for same walk in attached to multiple systems/racks
        } // NumSimulationRefrigAirchillers

        if ((state.dataRefrigCase->NumUnusedCoils > 0) && (!state.dataGlobal->DisplayExtraWarnings)) {
            //  write to error file,
            //  summary number of unused air chillers given if DataGlobals::DisplayExtraWarnings option not selected
            ShowWarningError(state,
                             format("{}Refrigeration:AirChiller -> {} unused refrigeration air chillers found during input processing.",
                                    RoutineName,
                                    state.dataRefrigCase->NumUnusedCoils));
            ShowContinueError(state, "   Those refrigeration air chillers are in the input file but are not connected to a ");
            ShowContinueError(state, "   Refrigeration:CompressorRack, Refrigeration:System or Refrigeration:SecondarySystem object.");
            ShowContinueError(state, "   These unused refrigeration air chillers will not be simulated.");
            ShowContinueError(state, "   Use Output:Diagnostics,DisplayUnusedObjects; to see them. ");
        } // NumUnusedAirChllerss
    } // NumSimulationAirChillers > 0

    if (state.dataRefrigCase->NumSimulationSecondarySystems > 0) {
        // check for refrigeration Secondarys not connected to detailed systems and
        //  refrigeration Secondarys connected more than once
        state.dataRefrigCase->NumUnusedSecondarys = 0;
        for (int SecondaryNum = 1; SecondaryNum <= state.dataRefrigCase->NumSimulationSecondarySystems; ++SecondaryNum) {
            if (Secondary(SecondaryNum).NumSysAttach == 1) {
                continue;
            }
            if (Secondary(SecondaryNum).NumSysAttach < 1) {
                ++state.dataRefrigCase->NumUnusedSecondarys;
                if (state.dataGlobal->DisplayExtraWarnings) {
                    //  individual secondary names listed if DataGlobals::DisplayExtraWarnings option selected
                    ShowWarningError(state, format("{}: Refrigeration:Secondary=\"{}\" unused. ", RoutineName, Secondary(SecondaryNum).Name));
                } // display extra warnings - give a list of unused Secondaries
            } // unused secondary
            if (Secondary(SecondaryNum).NumSysAttach > 1) {
                ErrorsFound = true;
                ShowSevereError(state,
                                format("{}: Refrigeration:Secondary=\"{}\", Same Refrigeration Secondary name referenced",
                                       RoutineName,
                                       Secondary(SecondaryNum).Name));
                ShowContinueError(state, "   by more than one refrigeration system");
            } // looking for same secondary loop attached to multiple systems/racks
        } // NumSimulationSecondarys

        if ((state.dataRefrigCase->NumUnusedSecondarys > 0) && (!state.dataGlobal->DisplayExtraWarnings)) {
            //  write to error file,
            //  summary number of unused secondaries given if DataGlobals::DisplayExtraWarnings option not selected
            ShowWarningError(state,
                             format("{}Refrigeration:Secondary -> {} unused refrigeration Secondary Loops found during input processing.",
                                    RoutineName,
                                    state.dataRefrigCase->NumUnusedSecondarys));
            ShowContinueError(state, "  Those refrigeration Secondary Loops are in the input file but are not connected to a refrigeration system.");
            ShowContinueError(state, "   These unused refrigeration secondaries will not be simulated.");
            ShowContinueError(state, "   Use Output:Diagnostics,DisplayUnusedObjects; to see them. ");
        } // NumUnusedSecondarys
    } // NumSimulationSecondarySystems > 0

    if (state.dataRefrigCase->NumRefrigCondensers > 0) {
        // Check for presence of shared condensers and for unused condensers
        //     - determines number of loops through refrigeration simulation
        //       because of dependence of performance on total condenser load
        state.dataRefrigCase->NumSimulationSharedCondensers = 0;
        state.dataRefrigCase->NumUnusedCondensers = 0;
        for (int CondNum = 1; CondNum <= state.dataRefrigCase->NumRefrigCondensers; ++CondNum) {
            if (Condenser(CondNum).NumSysAttach == 1) {
                continue;
            }
            if (Condenser(CondNum).NumSysAttach < 1) {
                ++state.dataRefrigCase->NumUnusedCondensers;
                if (state.dataGlobal->DisplayExtraWarnings) {
                    //  individual condenser names listed if DataGlobals::DisplayExtraWarnings option selected
                    ShowWarningError(state, format("{}: Refrigeration:Condenser=\"{}\" unused. ", RoutineName, Condenser(CondNum).Name));
                } // display extra warnings - give a list of unused condensers
            } // unused condenser
            if (Condenser(CondNum).NumSysAttach > 1) {
                ++state.dataRefrigCase->NumSimulationSharedCondensers;
            } // looking for shared condensers
        } // CondNum

        if ((state.dataRefrigCase->NumUnusedCondensers > 0) && (!state.dataGlobal->DisplayExtraWarnings)) {
            //  write to error file,
            //  summary number of unused condensers given if DataGlobals::DisplayExtraWarnings option not selected
            ShowWarningError(state,
                             format("{}Refrigeration condenser -> {} unused refrigeration condensers found during input processing.",
                                    RoutineName,
                                    state.dataRefrigCase->NumUnusedCondensers));
            ShowContinueError(state, "  Those refrigeration condensers are in the input file but are not connected to a refrigeration system.");
            ShowContinueError(state, "   These unused refrigeration condensers will not be simulated.");
            ShowContinueError(state, "   Use Output:Diagnostics,DisplayUnusedObjects; to see them. ");
        } // NumUnusedCondensers and displayextra warnings
    } // DataHeatBalance::NumRefrigCondensers > 0

    if (state.dataRefrigCase->NumSimulationGasCooler > 0) {
        // Check for presence of shared gas coolers and for unused gas coolers
        state.dataRefrigCase->NumSimulationSharedGasCoolers = 0;
        state.dataRefrigCase->NumUnusedGasCoolers = 0;
        for (int GCNum = 1; GCNum <= state.dataRefrigCase->NumSimulationGasCooler; ++GCNum) {
            if (GasCooler(GCNum).NumSysAttach == 1) {
                continue;
            }
            if (GasCooler(GCNum).NumSysAttach < 1) {
                ++state.dataRefrigCase->NumUnusedGasCoolers;
                if (state.dataGlobal->DisplayExtraWarnings) {
                    //  individual gas cooler names listed if DataGlobals::DisplayExtraWarnings option selected
                    ShowWarningError(state, format("{}: Refrigeration:GasCooler=\"{}\" unused. ", RoutineName, GasCooler(GCNum).Name));
                } // display extra warnings - give a list of unused gas coolers
            } // unused gas cooler
            if (GasCooler(GCNum).NumSysAttach > 1) {
                ++state.dataRefrigCase->NumSimulationSharedGasCoolers;
            } // looking for shared gas coolers
        } // GCNum

        if ((state.dataRefrigCase->NumUnusedGasCoolers > 0) && (!state.dataGlobal->DisplayExtraWarnings)) {
            //  write to error file,
            //  summary number of unused gas coolers given if DataGlobals::DisplayExtraWarnings option not selected
            ShowWarningError(state,
                             format("{}Refrigeration gas cooler -> {} unused refrigeration gas cooler(s) found during input processing.",
                                    RoutineName,
                                    state.dataRefrigCase->NumUnusedGasCoolers));
            ShowContinueError(state, "  These refrigeration gas coolers are in the input file but are not connected to a refrigeration system.");
            ShowContinueError(state, "  These unused refrigeration gas coolers will not be simulated.");
            ShowContinueError(state, "  Use Output:Diagnostics,DisplayUnusedObjects; to see them. ");
        } // NumUnusedGasCoolers and displayextra warnings
    } // NumSimulationGasCooler > 0

    // echo input to eio file.
    ReportRefrigerationComponents(state);

    if (ErrorsFound) {
        ShowFatalError(state, format("{} Previous errors cause program termination", RoutineName));
    }
}

void SetupReportInput(EnergyPlusData &state)
{
    // SUBROUTINE INFORMATION:
    //       AUTHOR         Richard Raustad, FSEC
    //       DATE WRITTEN   Oct/Nov 2004
    //       MODIFIED       Hudson, ORNL July 2007, Stovall, ORNL, 2008 and 09
    //       MODIFIED       Fricke, ORNL, Fall 2011, added transcritical CO2 refrigeration system variables
    //       RE-ENGINEERED  na

    // PURPOSE OF THIS SUBROUTINE:
    // Set up the report variables.

    auto &RefrigCase = state.dataRefrigCase->RefrigCase;
    auto &RefrigRack = state.dataRefrigCase->RefrigRack;
    auto &System = state.dataRefrigCase->System;
    auto &TransSystem = state.dataRefrigCase->TransSystem;
    auto &Condenser = state.dataRefrigCase->Condenser;
    auto &Compressor = state.dataRefrigCase->Compressor;
    auto &GasCooler = state.dataRefrigCase->GasCooler;
    auto &Subcooler = state.dataRefrigCase->Subcooler;
    auto &Secondary = state.dataRefrigCase->Secondary;
    auto &WalkIn = state.dataRefrigCase->WalkIn;
    auto &WarehouseCoil = state.dataRefrigCase->WarehouseCoil;
    auto &CoilSysCredit = state.dataRefrigCase->CoilSysCredit;
    auto &CaseWIZoneReport = state.dataRefrigCase->CaseWIZoneReport;

    std::string Walkin_and_zone_name; // concat name for walk-in/zone credit reporting

    if (state.dataRefrigCase->NumSimulationCases > 0) {
        // Setup Report Variables for simulated Refrigerated Case (do not report unused cases)
        // CurrentModuleObject='Refrigeration:Case'
        for (int caseNum = 1; caseNum <= state.dataRefrigCase->NumSimulationCases; ++caseNum) {
            auto &thisCase = RefrigCase(caseNum);
            if (thisCase.NumSysAttach == 1) {
                SetupOutputVariable(state,
                                    "Refrigeration Case Evaporator Total Cooling Rate",
                                    Constant::Units::W,
                                    thisCase.TotalCoolingLoad,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Average,
                                    thisCase.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Case Evaporator Total Cooling Energy",
                                    Constant::Units::J,
                                    thisCase.TotalCoolingEnergy,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Sum,
                                    thisCase.Name,
                                    Constant::eResource::EnergyTransfer,
                                    OutputProcessor::Group::Building,
                                    OutputProcessor::EndUseCat::Refrigeration,
                                    "", // End-use sub category
                                    thisCase.ZoneName);
                SetupOutputVariable(state,
                                    "Refrigeration Case Evaporator Sensible Cooling Rate",
                                    Constant::Units::W,
                                    thisCase.SensCoolingEnergyRate,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Average,
                                    thisCase.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Case Evaporator Sensible Cooling Energy",
                                    Constant::Units::J,
                                    thisCase.SensCoolingEnergy,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Sum,
                                    thisCase.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Case Evaporator Latent Cooling Rate",
                                    Constant::Units::W,
                                    thisCase.LatCoolingEnergyRate,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Average,
                                    thisCase.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Case Evaporator Latent Cooling Energy",
                                    Constant::Units::J,
                                    thisCase.LatCoolingEnergy,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Sum,
                                    thisCase.Name);

                SetupOutputVariable(state,
                                    "Refrigeration Case Zone Sensible Cooling Rate",
                                    Constant::Units::W,
                                    thisCase.SensZoneCreditCoolRate,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Average,
                                    thisCase.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Case Zone Sensible Cooling Energy",
                                    Constant::Units::J,
                                    thisCase.SensZoneCreditCool,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Sum,
                                    thisCase.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Case Zone Sensible Heating Rate",
                                    Constant::Units::W,
                                    thisCase.SensZoneCreditHeatRate,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Average,
                                    thisCase.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Case Zone Sensible Heating Energy",
                                    Constant::Units::J,
                                    thisCase.SensZoneCreditHeat,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Sum,
                                    thisCase.Name);

                SetupOutputVariable(state,
                                    "Refrigeration Case Zone Latent Rate",
                                    Constant::Units::W,
                                    thisCase.LatZoneCreditRate,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Average,
                                    thisCase.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Case Zone Latent Energy",
                                    Constant::Units::J,
                                    thisCase.LatZoneCredit,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Sum,
                                    thisCase.Name);

                SetupOutputVariable(state,
                                    "Refrigeration Case Return Air Sensible Cooling Rate",
                                    Constant::Units::W,
                                    thisCase.SensHVACCreditCoolRate,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Average,
                                    thisCase.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Case Return Air Sensible Cooling Energy",
                                    Constant::Units::J,
                                    thisCase.SensHVACCreditCool,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Sum,
                                    thisCase.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Case Return Air Sensible Heating Rate",
                                    Constant::Units::W,
                                    thisCase.SensHVACCreditHeatRate,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Average,
                                    thisCase.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Case Return Air Sensible Heating Energy",
                                    Constant::Units::J,
                                    thisCase.SensHVACCreditHeat,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Sum,
                                    thisCase.Name);

                SetupOutputVariable(state,
                                    "Refrigeration Case Return Air Latent Rate",
                                    Constant::Units::W,
                                    thisCase.LatHVACCreditRate,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Average,
                                    thisCase.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Case Return Air Latent Energy",
                                    Constant::Units::J,
                                    thisCase.LatHVACCredit,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Sum,
                                    thisCase.Name);

                SetupOutputVariable(state,
                                    "Refrigeration Case Evaporator Fan Electricity Rate",
                                    Constant::Units::W,
                                    thisCase.ElecFanPower,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Average,
                                    thisCase.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Case Evaporator Fan Electricity Energy",
                                    Constant::Units::J,
                                    thisCase.ElecFanConsumption,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Sum,
                                    thisCase.Name,
                                    Constant::eResource::Electricity,
                                    OutputProcessor::Group::Building,
                                    OutputProcessor::EndUseCat::Refrigeration,
                                    "General",
                                    thisCase.ZoneName);
                SetupOutputVariable(state,
                                    "Refrigeration Case Lighting Electricity Rate",
                                    Constant::Units::W,
                                    thisCase.ElecLightingPower,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Average,
                                    thisCase.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Case Lighting Electricity Energy",
                                    Constant::Units::J,
                                    thisCase.ElecLightingConsumption,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Sum,
                                    thisCase.Name,
                                    Constant::eResource::Electricity,
                                    OutputProcessor::Group::Building,
                                    OutputProcessor::EndUseCat::Refrigeration,
                                    "General",
                                    thisCase.ZoneName);

                // Report defrost energy curve value only for cases having electric or hot-gas defrost with temperature termination
                if (thisCase.defrostType == RefCaseDefrostType::ElectricTerm || thisCase.defrostType == RefCaseDefrostType::HotFluidTerm) {
                    SetupOutputVariable(state,
                                        "Refrigeration Case Defrost Energy Correction Curve Value",
                                        Constant::Units::None,
                                        thisCase.DefEnergyCurveValue,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Average,
                                        thisCase.Name);
                }

                SetupOutputVariable(state,
                                    "Refrigeration Case Latent Credit Curve Value",
                                    Constant::Units::None,
                                    thisCase.LatEnergyCurveValue,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Average,
                                    thisCase.Name);

                // Report only for cases having anti-sweat heaters
                if (thisCase.AntiSweatControlType > ASHtrCtrlType::None) {
                    SetupOutputVariable(state,
                                        "Refrigeration Case Anti Sweat Electricity Rate",
                                        Constant::Units::W,
                                        thisCase.ElecAntiSweatPower,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Average,
                                        thisCase.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Case Anti Sweat Electricity Energy",
                                        Constant::Units::J,
                                        thisCase.ElecAntiSweatConsumption,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Sum,
                                        thisCase.Name,
                                        Constant::eResource::Electricity,
                                        OutputProcessor::Group::Building,
                                        OutputProcessor::EndUseCat::Refrigeration,
                                        "General",
                                        thisCase.ZoneName);
                }

                // Report only for cases using electric defrost

                if (thisCase.defrostType == RefCaseDefrostType::Electric || thisCase.defrostType == RefCaseDefrostType::ElectricOnDemand ||
                    thisCase.defrostType == RefCaseDefrostType::ElectricTerm) {
                    SetupOutputVariable(state,
                                        "Refrigeration Case Defrost Electricity Rate",
                                        Constant::Units::W,
                                        thisCase.ElecDefrostPower,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Average,
                                        thisCase.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Case Defrost Electricity Energy",
                                        Constant::Units::J,
                                        thisCase.ElecDefrostConsumption,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Sum,
                                        thisCase.Name,
                                        Constant::eResource::Electricity,
                                        OutputProcessor::Group::Building,
                                        OutputProcessor::EndUseCat::Refrigeration,
                                        "General",
                                        thisCase.ZoneName);
                }

                // register refrigeration case credits as internal gains
                if (thisCase.ActualZoneNum > 0) {
                    SetupZoneInternalGain(state,
                                          thisCase.ActualZoneNum,
                                          thisCase.Name,
                                          DataHeatBalance::IntGainType::RefrigerationCase,
                                          &thisCase.SensZoneCreditRate,
                                          &thisCase.SensHVACCreditRate,
                                          nullptr,
                                          &thisCase.LatZoneCreditRate,
                                          &thisCase.LatHVACCreditRate,
                                          nullptr,
                                          nullptr,
                                          thisCase.ZoneRANode);
                }
            } // END IF (.NOT. RefrigCase(CaseNum)%unusedCase)
        }
    } // NumSimulationCases > 0

    if (state.dataRefrigCase->NumSimulationWalkIns > 0) {
        // Setup Report Variables for simulated  Walk In (do not report unused WalkIns)
        // CurrentModuleObject='Refrigeration:WalkIn'
        for (int walkInNum = 1; walkInNum <= state.dataRefrigCase->NumSimulationWalkIns; ++walkInNum) {
            auto &walkin = WalkIn(walkInNum);
            if (walkin.NumSysAttach == 1) { // ensure no unuseds reported
                SetupOutputVariable(state,
                                    "Refrigeration Walk In Evaporator Total Cooling Rate",
                                    Constant::Units::W,
                                    walkin.TotalCoolingLoad,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Average,
                                    walkin.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Walk In Evaporator Total Cooling Energy",
                                    Constant::Units::J,
                                    walkin.TotalCoolingEnergy,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Sum,
                                    walkin.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Walk In Evaporator Sensible Cooling Rate",
                                    Constant::Units::W,
                                    walkin.TotSensCoolingEnergyRate,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Average,
                                    walkin.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Walk In Evaporator Sensible Cooling Energy",
                                    Constant::Units::J,
                                    walkin.TotSensCoolingEnergy,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Sum,
                                    walkin.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Walk In Evaporator Latent Cooling Rate",
                                    Constant::Units::W,
                                    walkin.TotLatCoolingEnergyRate,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Average,
                                    walkin.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Walk In Evaporator Latent Cooling Energy",
                                    Constant::Units::J,
                                    walkin.TotLatCoolingEnergy,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Sum,
                                    walkin.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Walk In Ancillary Electricity Rate",
                                    Constant::Units::W,
                                    walkin.TotalElecPower,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Average,
                                    walkin.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Walk In Ancillary Electricity Energy",
                                    Constant::Units::J,
                                    walkin.TotalElecConsumption,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Sum,
                                    walkin.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Walk In Fan Electricity Rate",
                                    Constant::Units::W,
                                    walkin.ElecFanPower,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Average,
                                    walkin.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Walk In Fan Electricity Energy",
                                    Constant::Units::J,
                                    walkin.ElecFanConsumption,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Sum,
                                    walkin.Name,
                                    Constant::eResource::Electricity,
                                    OutputProcessor::Group::Building,
                                    OutputProcessor::EndUseCat::Refrigeration,
                                    "General");
                SetupOutputVariable(state,
                                    "Refrigeration Walk In Lighting Electricity Rate",
                                    Constant::Units::W,
                                    walkin.ElecLightingPower,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Average,
                                    walkin.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Walk In Lighting Electricity Energy",
                                    Constant::Units::J,
                                    walkin.ElecLightingConsumption,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Sum,
                                    walkin.Name,
                                    Constant::eResource::Electricity,
                                    OutputProcessor::Group::Building,
                                    OutputProcessor::EndUseCat::Refrigeration,
                                    "General");
                SetupOutputVariable(state,
                                    "Refrigeration Walk In Heater Electricity Rate",
                                    Constant::Units::W,
                                    walkin.ElecHeaterPower,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Average,
                                    walkin.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Walk In Heater Electricity Energy",
                                    Constant::Units::J,
                                    walkin.ElecHeaterConsumption,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Sum,
                                    walkin.Name,
                                    Constant::eResource::Electricity,
                                    OutputProcessor::Group::Building,
                                    OutputProcessor::EndUseCat::Refrigeration,
                                    "General");

                // Report only for WalkIns using electric defrost
                if (walkin.defrostType == DefrostType::Elec) {
                    SetupOutputVariable(state,
                                        "Refrigeration Walk In Defrost Electricity Rate",
                                        Constant::Units::W,
                                        walkin.ElecDefrostPower,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Average,
                                        walkin.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Walk In Defrost Electricity Energy",
                                        Constant::Units::J,
                                        walkin.ElecDefrostConsumption,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Sum,
                                        walkin.Name,
                                        Constant::eResource::Electricity,
                                        OutputProcessor::Group::Building,
                                        OutputProcessor::EndUseCat::Refrigeration,
                                        "General");
                }

                // Report walkin variables that are specified for each zone exposed to the walkin
                // For "IDOut" variable in SetupOutputVariable, need to create a single name that includes
                //    both the walk-in name and the zone name - see "Walkin_and_zone_name" concatenation
                //    This new variable name is important if using an rvi file!
                for (int zoneId = 1; zoneId <= walkin.NumZones; ++zoneId) {

                    Walkin_and_zone_name = walkin.Name + "InZone" + walkin.ZoneName(zoneId);

                    SetupOutputVariable(state,
                                        "Refrigeration Walk In Zone Sensible Cooling Rate",
                                        Constant::Units::W,
                                        walkin.SensZoneCreditCoolRate(zoneId),
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Average,
                                        Walkin_and_zone_name);
                    SetupOutputVariable(state,
                                        "Refrigeration Walk In Zone Sensible Cooling Energy",
                                        Constant::Units::J,
                                        walkin.SensZoneCreditCool(zoneId),
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Sum,
                                        Walkin_and_zone_name);
                    SetupOutputVariable(state,
                                        "Refrigeration Walk In Zone Sensible Heating Rate",
                                        Constant::Units::W,
                                        walkin.SensZoneCreditHeatRate(zoneId),
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Average,
                                        Walkin_and_zone_name);
                    SetupOutputVariable(state,
                                        "Refrigeration Walk In Zone Sensible Heating Energy",
                                        Constant::Units::J,
                                        walkin.SensZoneCreditHeat(zoneId),
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Sum,
                                        Walkin_and_zone_name);
                    SetupOutputVariable(state,
                                        "Refrigeration Walk In Zone Latent Rate",
                                        Constant::Units::W,
                                        walkin.LatZoneCreditRate(zoneId),
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Average,
                                        Walkin_and_zone_name);
                    SetupOutputVariable(state,
                                        "Refrigeration Walk In Zone Latent Energy",
                                        Constant::Units::J,
                                        walkin.LatZoneCredit(zoneId),
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Sum,
                                        Walkin_and_zone_name);

                    if (walkin.ZoneNum(zoneId) > 0) {
                        SetupZoneInternalGain(state,
                                              walkin.ZoneNum(zoneId),
                                              Walkin_and_zone_name,
                                              DataHeatBalance::IntGainType::RefrigerationWalkIn,
                                              &walkin.SensZoneCreditRate(zoneId),
                                              nullptr,
                                              nullptr,
                                              &walkin.LatZoneCreditRate(zoneId));
                    }

                } // ZoneID
            } //(.NOT.  WalkIn( WalkInNum)%unusedWalkIn)
        } // NumSimulationWalkIns
    } // NumSimulationWalkIns > 0

    if (state.dataRefrigCase->NumSimulationRefrigAirChillers > 0) {
        // Setup Report Variables for simulated Warehouse coils (do not report unused warehouse coils)
        // CurrentModuleObject='Refrigeration:AirChiller'
        for (int coilNum = 1; coilNum <= state.dataRefrigCase->NumSimulationRefrigAirChillers; ++coilNum) {
            auto &coil = WarehouseCoil(coilNum);
            if (coil.NumSysAttach == 1) { // ensure no unuseds reported
                SetupOutputVariable(state,
                                    "Refrigeration Zone Air Chiller Total Cooling Rate",
                                    Constant::Units::W,
                                    coil.TotalCoolingLoad,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Average,
                                    coil.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Zone Air Chiller Total Cooling Energy",
                                    Constant::Units::J,
                                    coil.TotalCoolingEnergy,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Sum,
                                    coil.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Zone Air Chiller Sensible Cooling Rate",
                                    Constant::Units::W,
                                    coil.SensCoolingEnergyRate,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Average,
                                    coil.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Zone Air Chiller Sensible Cooling Energy",
                                    Constant::Units::J,
                                    coil.SensCoolingEnergy,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Sum,
                                    coil.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Zone Air Chiller Latent Cooling Rate",
                                    Constant::Units::W,
                                    coil.LatCreditRate,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Average,
                                    coil.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Zone Air Chiller Latent Cooling Energy",
                                    Constant::Units::J,
                                    coil.LatCreditEnergy,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Sum,
                                    coil.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Zone Air Chiller Water Removed Mass Flow Rate",
                                    Constant::Units::kg_s,
                                    coil.LatKgPerS_ToZone,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Average,
                                    coil.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Zone Air Chiller Total Electricity Rate",
                                    Constant::Units::W,
                                    coil.TotalElecPower,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Average,
                                    coil.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Zone Air Chiller Total Electricity Energy",
                                    Constant::Units::J,
                                    coil.TotalElecConsumption,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Sum,
                                    coil.Name); // components are metered separately
                SetupOutputVariable(state,
                                    "Refrigeration Zone Air Chiller Fan Electricity Rate",
                                    Constant::Units::W,
                                    coil.ElecFanPower,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Average,
                                    coil.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Zone Air Chiller Fan Electric Energy",
                                    Constant::Units::J,
                                    coil.ElecFanConsumption,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Sum,
                                    coil.Name,
                                    Constant::eResource::Electricity,
                                    OutputProcessor::Group::Building,
                                    OutputProcessor::EndUseCat::Refrigeration,
                                    "General");
                SetupOutputVariable(state,
                                    "Refrigeration Zone Air Chiller Heater Electricity Rate",
                                    Constant::Units::W,
                                    coil.ElecHeaterPower,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Average,
                                    coil.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Zone Air Chiller Heater Electricity Energy",
                                    Constant::Units::J,
                                    coil.ElecHeaterConsumption,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Sum,
                                    coil.Name,
                                    Constant::eResource::Electricity,
                                    OutputProcessor::Group::Building,
                                    OutputProcessor::EndUseCat::Refrigeration,
                                    "General");
                SetupOutputVariable(state,
                                    "Refrigeration Zone Air Chiller Sensible Heat Ratio",
                                    Constant::Units::None,
                                    coil.SensHeatRatio,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Average,
                                    coil.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Zone Air Chiller Frost Accumulation Mass",
                                    Constant::Units::kg,
                                    coil.KgFrost,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Average,
                                    coil.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Zone Air Chiller Zone Total Cooling Rate",
                                    Constant::Units::W,
                                    coil.ReportTotalCoolCreditRate,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Average,
                                    coil.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Zone Air Chiller Zone Total Cooling Energy",
                                    Constant::Units::J,
                                    coil.ReportTotalCoolCreditEnergy,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Sum,
                                    coil.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Zone Air Chiller Zone Sensible Cooling Rate",
                                    Constant::Units::W,
                                    coil.ReportSensCoolCreditRate,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Average,
                                    coil.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Zone Air Chiller Zone Sensible Cooling Energy",
                                    Constant::Units::J,
                                    coil.ReportSensCoolCreditEnergy,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Sum,
                                    coil.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Zone Air Chiller Zone Heating Rate",
                                    Constant::Units::W,
                                    coil.ReportHeatingCreditRate,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Average,
                                    coil.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Zone Air Chiller Zone Heating Energy",
                                    Constant::Units::J,
                                    coil.ReportHeatingCreditEnergy,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Sum,
                                    coil.Name);

                // Report only for Warehouse coils using electric defrost
                if (coil.defrostType == DefrostType::Elec) {
                    SetupOutputVariable(state,
                                        "Refrigeration Zone Air Chiller Defrost Electricity Rate",
                                        Constant::Units::W,
                                        coil.ElecDefrostPower,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Average,
                                        coil.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Zone Air Chiller Defrost Electricity Energy",
                                        Constant::Units::J,
                                        coil.ElecDefrostConsumption,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Sum,
                                        coil.Name,
                                        Constant::eResource::Electricity,
                                        OutputProcessor::Group::Building,
                                        OutputProcessor::EndUseCat::Refrigeration,
                                        "General");
                } // electric defrost coil
            } //(.NOT.  coil%unusedWarehouseCoil)
        } // NumSimulationWarehouseCoils
    } // NumSimulationRefrigAirChillers > 0

    // There are no report variables for Chiller sets because they are
    // used to pass the demand to the coils, but are NOT used to provide the
    // cooling energy to the zone (because more than one set may cool a zone)

    // Report sum of all refrigeration interactions with each zone

    for (int zoneID = 1; zoneID <= state.dataGlobal->NumOfZones; ++zoneID) {
        if (state.dataRefrigCase->RefrigPresentInZone(zoneID)) {
            if (state.dataRefrigCase->HaveCasesOrWalkins) {
                SetupOutputVariable(state,
                                    "Refrigeration Zone Case and Walk In Total Sensible Cooling Rate",
                                    Constant::Units::W,
                                    state.dataHeatBal->RefrigCaseCredit(zoneID).SenCaseCreditToZone,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Average,
                                    state.dataHeatBal->Zone(zoneID).Name);
                SetupOutputVariable(state,
                                    "Refrigeration Zone Case and Walk In Total Sensible Cooling Energy",
                                    Constant::Units::J,
                                    CaseWIZoneReport(zoneID).SenCaseCreditToZoneEnergy,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Sum,
                                    state.dataHeatBal->Zone(zoneID).Name);
                SetupOutputVariable(state,
                                    "Refrigeration Zone Case and Walk In Heating Rate",
                                    Constant::Units::W,
                                    CaseWIZoneReport(zoneID).HeatingToZoneRate,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Average,
                                    state.dataHeatBal->Zone(zoneID).Name);
                SetupOutputVariable(state,
                                    "Refrigeration Zone Case and Walk In Heating Energy",
                                    Constant::Units::J,
                                    CaseWIZoneReport(zoneID).HeatingToZoneEnergy,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Sum,
                                    state.dataHeatBal->Zone(zoneID).Name);
                SetupOutputVariable(state,
                                    "Refrigeration Zone Case and Walk In Sensible Cooling Rate",
                                    Constant::Units::W,
                                    CaseWIZoneReport(zoneID).SenCoolingToZoneRate,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Average,
                                    state.dataHeatBal->Zone(zoneID).Name);
                SetupOutputVariable(state,
                                    "Refrigeration Zone Case and Walk In Sensible Cooling Energy",
                                    Constant::Units::J,
                                    CaseWIZoneReport(zoneID).SenCoolingToZoneEnergy,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Sum,
                                    state.dataHeatBal->Zone(zoneID).Name);
                SetupOutputVariable(state,
                                    "Refrigeration Zone Case and Walk In Total Latent Cooling Rate",
                                    Constant::Units::W,
                                    CaseWIZoneReport(zoneID).LatCoolingToZoneRate,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Average,
                                    state.dataHeatBal->Zone(zoneID).Name);
                SetupOutputVariable(state,
                                    "Refrigeration Zone Case and Walk In Total Latent Cooling Energy",
                                    Constant::Units::J,
                                    CaseWIZoneReport(zoneID).LatCoolingToZoneEnergy,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Sum,
                                    state.dataHeatBal->Zone(zoneID).Name);
                SetupOutputVariable(state,
                                    "Refrigeration Zone Case and Walk In Total Cooling Rate",
                                    Constant::Units::W,
                                    CaseWIZoneReport(zoneID).TotCoolingToZoneRate,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Average,
                                    state.dataHeatBal->Zone(zoneID).Name);
                SetupOutputVariable(state,
                                    "Refrigeration Zone Case and Walk In Total Cooling Energy",
                                    Constant::Units::J,
                                    CaseWIZoneReport(zoneID).TotCoolingToZoneEnergy,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Sum,
                                    state.dataHeatBal->Zone(zoneID).Name);
                SetupOutputVariable(state,
                                    "Refrigeration Zone Case and Walk In Total Heat Transfer Rate",
                                    Constant::Units::W,
                                    CaseWIZoneReport(zoneID).TotHtXferToZoneRate,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Average,
                                    state.dataHeatBal->Zone(zoneID).Name);
                SetupOutputVariable(state,
                                    "Refrigeration Zone Case and Walk In Total Heat Transfer Energy",
                                    Constant::Units::J,
                                    CaseWIZoneReport(zoneID).TotHtXferToZoneEnergy,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Sum,
                                    state.dataHeatBal->Zone(zoneID).Name);
            } // HaveCasesOrWalkIns

            if (state.dataRefrigCase->HaveChillers) {
                SetupOutputVariable(state,
                                    "Refrigeration Zone Air Chiller Sensible Heat Transfer Rate",
                                    Constant::Units::W,
                                    CoilSysCredit(zoneID).SenCreditToZoneRate,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Average,
                                    state.dataHeatBal->Zone(zoneID).Name);
                SetupOutputVariable(state,
                                    "Refrigeration Zone Air Chiller Sensible Heat Transfer Energy",
                                    Constant::Units::J,
                                    CoilSysCredit(zoneID).SenCreditToZoneEnergy,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Sum,
                                    state.dataHeatBal->Zone(zoneID).Name);
                SetupOutputVariable(state,
                                    "Refrigeration Zone Air Chiller Sensible Cooling Rate",
                                    Constant::Units::W,
                                    CoilSysCredit(zoneID).ReportSenCoolingToZoneRate,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Average,
                                    state.dataHeatBal->Zone(zoneID).Name);
                SetupOutputVariable(state,
                                    "Refrigeration Zone Air Chiller Sensible Cooling Energy",
                                    Constant::Units::J,
                                    CoilSysCredit(zoneID).ReportSenCoolingToZoneEnergy,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Sum,
                                    state.dataHeatBal->Zone(zoneID).Name);
                SetupOutputVariable(state,
                                    "Refrigeration Zone Air Chiller Latent Cooling Rate",
                                    Constant::Units::W,
                                    CoilSysCredit(zoneID).ReportLatCreditToZoneRate,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Average,
                                    state.dataHeatBal->Zone(zoneID).Name);
                SetupOutputVariable(state,
                                    "Refrigeration Zone Air Chiller Latent Cooling Energy",
                                    Constant::Units::J,
                                    CoilSysCredit(zoneID).ReportLatCreditToZoneEnergy,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Sum,
                                    state.dataHeatBal->Zone(zoneID).Name);
                SetupOutputVariable(state,
                                    "Refrigeration Zone Air Chiller Water Removed Mass Flow Rate",
                                    Constant::Units::kg_s,
                                    CoilSysCredit(zoneID).ReportH2ORemovedKgPerS_FromZoneRate,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Average,
                                    state.dataHeatBal->Zone(zoneID).Name);
                SetupOutputVariable(state,
                                    "Refrigeration Zone Air Chiller Total Cooling Rate",
                                    Constant::Units::W,
                                    CoilSysCredit(zoneID).ReportTotCoolingToZoneRate,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Average,
                                    state.dataHeatBal->Zone(zoneID).Name);
                SetupOutputVariable(state,
                                    "Refrigeration Zone Air Chiller Total Cooling Energy",
                                    Constant::Units::J,
                                    CoilSysCredit(zoneID).ReportTotCoolingToZoneEnergy,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Sum,
                                    state.dataHeatBal->Zone(zoneID).Name);
                SetupOutputVariable(state,
                                    "Refrigeration Zone Air Chiller Heating Rate",
                                    Constant::Units::W,
                                    CoilSysCredit(zoneID).ReportHeatingToZoneRate,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Average,
                                    state.dataHeatBal->Zone(zoneID).Name);
                SetupOutputVariable(state,
                                    "Refrigeration Zone Air Chiller Heating Energy",
                                    Constant::Units::J,
                                    CoilSysCredit(zoneID).ReportHeatingToZoneEnergy,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Sum,
                                    state.dataHeatBal->Zone(zoneID).Name);
            } // HaveChillers
        } // RefrigPresentInZone(ZoneID)
    } // ZoneID

    if (state.dataRefrigCase->NumSimulationSecondarySystems > 0) {
        // CurrentModuleObject='Refrigeration:SecondarySystem'
        for (int secondNum = 1; secondNum <= state.dataRefrigCase->NumSimulationSecondarySystems; ++secondNum) {
            auto &secondary = Secondary(secondNum);
            if (secondary.NumSysAttach == 1) {
                if (secondary.CoilFlag) { // secondary system serves chillers and is solved on HVAC time step
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller Secondary Loop Pump Electricity Rate",
                                        Constant::Units::W,
                                        secondary.PumpPowerTotal,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Average,
                                        secondary.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller Secondary Loop Pump Electricity Energy",
                                        Constant::Units::J,
                                        secondary.PumpElecEnergyTotal,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Sum,
                                        secondary.Name,
                                        Constant::eResource::Electricity,
                                        OutputProcessor::Group::Plant,
                                        OutputProcessor::EndUseCat::Refrigeration,
                                        secondary.EndUseSubcategory);
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller Secondary Loop Load Heat Transfer Rate",
                                        Constant::Units::W,
                                        secondary.TotalRefrigLoad,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Average,
                                        secondary.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller Secondary Loop Load Heat Transfer Energy",
                                        Constant::Units::J,
                                        secondary.TotalRefrigEnergy,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Sum,
                                        secondary.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller Secondary Loop Total Heat Transfer Rate",
                                        Constant::Units::W,
                                        secondary.TotalCoolingLoad,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Average,
                                        secondary.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller Secondary Loop Total Heat Transfer Energy",
                                        Constant::Units::J,
                                        secondary.TotalCoolingEnergy,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Sum,
                                        secondary.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller Secondary Loop Estimated Refrigerant Inventory Mass",
                                        Constant::Units::kg,
                                        secondary.RefInventory,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Average,
                                        secondary.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller Secondary Loop Volume Flow Rate",
                                        Constant::Units::m3_s,
                                        secondary.FlowVolActual,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Average,
                                        secondary.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller Secondary Loop Pipe Heat Gain Rate",
                                        Constant::Units::W,
                                        secondary.DistPipeHeatGain,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Average,
                                        secondary.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller Secondary Loop Pipe Heat Gain Energy",
                                        Constant::Units::J,
                                        secondary.DistPipeHeatGainEnergy,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Sum,
                                        secondary.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller Secondary Loop Receiver Heat Gain Rate",
                                        Constant::Units::W,
                                        secondary.ReceiverHeatGain,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Average,
                                        secondary.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller Secondary Loop Receiver Heat Gain Energy",
                                        Constant::Units::J,
                                        secondary.ReceiverHeatGainEnergy,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Sum,
                                        secondary.Name);
                } else { // Secondary loop serves cases and walk-ins on zone(load) time step
                    SetupOutputVariable(state,
                                        "Refrigeration Secondary Loop Pump Electricity Rate",
                                        Constant::Units::W,
                                        secondary.PumpPowerTotal,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Average,
                                        secondary.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Secondary Loop Pump Electricity Energy",
                                        Constant::Units::J,
                                        secondary.PumpElecEnergyTotal,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Sum,
                                        secondary.Name,
                                        Constant::eResource::Electricity,
                                        OutputProcessor::Group::Plant,
                                        OutputProcessor::EndUseCat::Refrigeration,
                                        secondary.EndUseSubcategory);
                    SetupOutputVariable(state,
                                        "Refrigeration Secondary Loop Load Heat Transfer Rate",
                                        Constant::Units::W,
                                        secondary.TotalRefrigLoad,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Average,
                                        secondary.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Secondary Loop Load Heat Transfer Energy",
                                        Constant::Units::J,
                                        secondary.TotalRefrigEnergy,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Sum,
                                        secondary.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Secondary Loop Total Heat Transfer Rate",
                                        Constant::Units::W,
                                        secondary.TotalCoolingLoad,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Average,
                                        secondary.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Secondary Loop Total Heat Transfer Energy",
                                        Constant::Units::J,
                                        secondary.TotalCoolingEnergy,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Sum,
                                        secondary.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Secondary Loop Estimated Refrigerant Inventory Mass",
                                        Constant::Units::kg,
                                        secondary.RefInventory,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Average,
                                        secondary.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Secondary Loop Volume Flow Rate",
                                        Constant::Units::m3_s,
                                        secondary.FlowVolActual,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Average,
                                        secondary.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Secondary Loop Pipe Heat Gain Rate",
                                        Constant::Units::W,
                                        secondary.DistPipeHeatGain,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Average,
                                        secondary.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Secondary Loop Pipe Heat Gain Energy",
                                        Constant::Units::J,
                                        secondary.DistPipeHeatGainEnergy,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Sum,
                                        secondary.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Secondary Loop Receiver Heat Gain Rate",
                                        Constant::Units::W,
                                        secondary.ReceiverHeatGain,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Average,
                                        secondary.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Secondary Loop Receiver Heat Gain Energy",
                                        Constant::Units::J,
                                        secondary.ReceiverHeatGainEnergy,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Sum,
                                        secondary.Name);
                } // NOT coilflag so on Zone timestep
                if (secondary.ReceiverZoneNum > 0) {
                    SetupZoneInternalGain(state,
                                          secondary.ReceiverZoneNum,
                                          secondary.Name,
                                          DataHeatBalance::IntGainType::RefrigerationSecondaryReceiver,
                                          &secondary.ReceiverZoneHeatGain);
                }
                if (secondary.DistPipeZoneNum > 0) {
                    SetupZoneInternalGain(state,
                                          secondary.DistPipeZoneNum,
                                          secondary.Name,
                                          DataHeatBalance::IntGainType::RefrigerationSecondaryPipe,
                                          &secondary.DistPipeZoneHeatGain);
                }
            } // not an unused
        } // NumSimulationSecondarySystems
    } // NumSimulationSecondarySystems > 0

    // Setup Report Variables for Refrigeration Compressor Rack
    if (state.dataRefrigCase->NumRefrigeratedRacks > 0) {
        // CurrentModuleObject='Refrigeration:CompressorRack'
        for (int rackNum = 1; rackNum <= state.dataRefrigCase->NumRefrigeratedRacks; ++rackNum) {
            auto &rack = RefrigRack(rackNum);
            if (rack.CoilFlag) { // rack serves chillers and is solved on HVAC time step
                SetupOutputVariable(state,
                                    "Refrigeration Air Chiller Compressor Rack Electricity Rate",
                                    Constant::Units::W,
                                    rack.RackCompressorPower,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Average,
                                    rack.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Air Chiller Compressor Rack Electricity Energy",
                                    Constant::Units::J,
                                    rack.RackElecConsumption,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Sum,
                                    rack.Name,
                                    Constant::eResource::Electricity,
                                    OutputProcessor::Group::Plant,
                                    OutputProcessor::EndUseCat::Refrigeration,
                                    rack.EndUseSubcategory);
                SetupOutputVariable(state,
                                    "Refrigeration Air Chiller Compressor Rack Condenser Fan Electricity Rate",
                                    Constant::Units::W,
                                    rack.ActualCondenserFanPower,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Average,
                                    rack.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Air Chiller Compressor Rack Condenser Fan Electricity Energy",
                                    Constant::Units::J,
                                    rack.CondenserFanConsumption,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Sum,
                                    rack.Name,
                                    Constant::eResource::Electricity,
                                    OutputProcessor::Group::Plant,
                                    OutputProcessor::EndUseCat::Refrigeration,
                                    rack.EndUseSubcategory);
                SetupOutputVariable(state,
                                    "Refrigeration Air Chiller Compressor Rack Total Heat Transfer Rate",
                                    Constant::Units::W,
                                    rack.RackCapacity,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Average,
                                    rack.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Air Chiller Compressor Rack Total Heat Transfer Energy",
                                    Constant::Units::J,
                                    rack.RackCoolingEnergy,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Sum,
                                    rack.Name,
                                    Constant::eResource::EnergyTransfer,
                                    OutputProcessor::Group::Plant,
                                    OutputProcessor::EndUseCat::Refrigeration,
                                    rack.EndUseSubcategory);
                SetupOutputVariable(state,
                                    "Refrigeration Air Chiller Compressor Rack COP",
                                    Constant::Units::W_W,
                                    rack.RackCompressorCOP,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Average,
                                    rack.Name);

                if (rack.CondenserType == DataHeatBalance::RefrigCondenserType::Evap) {
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller Compressor Rack Evaporative Condenser Pump Electricity Rate",
                                        Constant::Units::W,
                                        rack.ActualEvapPumpPower,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Average,
                                        rack.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller Compressor Rack Evaporative Condenser Pump Electricity Energy",
                                        Constant::Units::J,
                                        rack.EvapPumpConsumption,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Sum,
                                        rack.Name,
                                        Constant::eResource::Electricity,
                                        OutputProcessor::Group::Plant,
                                        OutputProcessor::EndUseCat::Refrigeration,
                                        rack.EndUseSubcategory);
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller Compressor Rack Evaporative Condenser Basin Heater Electricity Rate",
                                        Constant::Units::W,
                                        rack.BasinHeaterPower,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Average,
                                        rack.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller Compressor Rack Evaporative Condenser Basin Heater Electricity Energy",
                                        Constant::Units::J,
                                        rack.BasinHeaterConsumption,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Sum,
                                        rack.Name,
                                        Constant::eResource::Electricity,
                                        OutputProcessor::Group::Plant,
                                        OutputProcessor::EndUseCat::Refrigeration,
                                        rack.EndUseSubcategory);
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller Compressor Rack Evaporative Condenser Water Volume Flow Rate",
                                        Constant::Units::m3_s,
                                        rack.EvapWaterConsumpRate,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Average,
                                        rack.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller Compressor Rack Evaporative Condenser Water Volume",
                                        Constant::Units::m3,
                                        rack.EvapWaterConsumption,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Sum,
                                        rack.Name,
                                        Constant::eResource::Water,
                                        OutputProcessor::Group::Plant,
                                        OutputProcessor::EndUseCat::Refrigeration,
                                        rack.EndUseSubcategory);
                } // Evap condenser

                if (rack.HeatRejectionLocation == HeatRejLocation::Zone) {
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller Compressor Rack Zone Sensible Heating Rate",
                                        Constant::Units::W,
                                        rack.SensZoneCreditHeatRate,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Average,
                                        rack.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller Compressor Rack Zone Sensible Heating Energy",
                                        Constant::Units::J,
                                        rack.SensZoneCreditHeat,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Sum,
                                        rack.Name);

                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller Compressor Rack Return Air Sensible Heating Rate",
                                        Constant::Units::W,
                                        rack.SensHVACCreditHeatRate,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Average,
                                        rack.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller Compressor Rack Return Air Sensible Heating Energy",
                                        Constant::Units::J,
                                        rack.SensHVACCreditHeat,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Sum,
                                        rack.Name);

                    // If CoilFlag is true and Location is Zone, GetRefrigerationInput ensures you must have a Heat Rejection Zone provided already
                    SetupZoneInternalGain(state,
                                          rack.HeatRejectionZoneNum,
                                          rack.Name,
                                          DataHeatBalance::IntGainType::RefrigerationCompressorRack,
                                          &rack.SensZoneCreditHeatRate,
                                          &rack.SensHVACCreditHeatRate);

                } // LocationZone

            } else { // Rack serves cases and walkins on zone (load) time step

                SetupOutputVariable(state,
                                    "Refrigeration Compressor Rack Electricity Rate",
                                    Constant::Units::W,
                                    rack.RackCompressorPower,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Average,
                                    rack.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Compressor Rack Electricity Energy",
                                    Constant::Units::J,
                                    rack.RackElecConsumption,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Sum,
                                    rack.Name,
                                    Constant::eResource::Electricity,
                                    OutputProcessor::Group::Plant,
                                    OutputProcessor::EndUseCat::Refrigeration,
                                    rack.EndUseSubcategory);
                SetupOutputVariable(state,
                                    "Refrigeration Compressor Rack Condenser Fan Electricity Rate",
                                    Constant::Units::W,
                                    rack.ActualCondenserFanPower,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Average,
                                    rack.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Compressor Rack Condenser Fan Electricity Energy",
                                    Constant::Units::J,
                                    rack.CondenserFanConsumption,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Sum,
                                    rack.Name,
                                    Constant::eResource::Electricity,
                                    OutputProcessor::Group::Plant,
                                    OutputProcessor::EndUseCat::Refrigeration,
                                    rack.EndUseSubcategory);
                SetupOutputVariable(state,
                                    "Refrigeration Compressor Rack Total Heat Transfer Rate",
                                    Constant::Units::W,
                                    rack.RackCapacity,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Average,
                                    rack.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Compressor Rack Total Heat Transfer Energy",
                                    Constant::Units::J,
                                    rack.RackCoolingEnergy,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Sum,
                                    rack.Name,
                                    Constant::eResource::EnergyTransfer,
                                    OutputProcessor::Group::Plant,
                                    OutputProcessor::EndUseCat::Refrigeration,
                                    rack.EndUseSubcategory);
                SetupOutputVariable(state,
                                    "Refrigeration Compressor Rack COP",
                                    Constant::Units::W_W,
                                    rack.RackCompressorCOP,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Average,
                                    rack.Name);

                if (rack.CondenserType == DataHeatBalance::RefrigCondenserType::Evap) {
                    SetupOutputVariable(state,
                                        "Refrigeration Compressor Rack Evaporative Condenser Pump Electricity Rate",
                                        Constant::Units::W,
                                        rack.ActualEvapPumpPower,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Average,
                                        rack.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Compressor Rack Evaporative Condenser Pump Electricity Energy",
                                        Constant::Units::J,
                                        rack.EvapPumpConsumption,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Sum,
                                        rack.Name,
                                        Constant::eResource::Electricity,
                                        OutputProcessor::Group::Plant,
                                        OutputProcessor::EndUseCat::Refrigeration,
                                        rack.EndUseSubcategory);
                    SetupOutputVariable(state,
                                        "Refrigeration Compressor Rack Evaporative Condenser Basin Heater Electricity Rate",
                                        Constant::Units::W,
                                        rack.BasinHeaterPower,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Average,
                                        rack.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Compressor Rack Evaporative Condenser Basin Heater Electricity Energy",
                                        Constant::Units::J,
                                        rack.BasinHeaterConsumption,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Sum,
                                        rack.Name,
                                        Constant::eResource::Electricity,
                                        OutputProcessor::Group::Plant,
                                        OutputProcessor::EndUseCat::Refrigeration,
                                        rack.EndUseSubcategory);
                    SetupOutputVariable(state,
                                        "Refrigeration Compressor Rack Evaporative Condenser Water Volume Flow Rate",
                                        Constant::Units::m3_s,
                                        rack.EvapWaterConsumpRate,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Average,
                                        rack.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Compressor Rack Evaporative Condenser Water Volume",
                                        Constant::Units::m3,
                                        rack.EvapWaterConsumption,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Sum,
                                        rack.Name,
                                        Constant::eResource::Water,
                                        OutputProcessor::Group::Plant,
                                        OutputProcessor::EndUseCat::Refrigeration,
                                        rack.EndUseSubcategory);
                } // condenser evap

                if (rack.HeatRejectionLocation == HeatRejLocation::Zone) {
                    SetupOutputVariable(state,
                                        "Refrigeration Compressor Rack Zone Sensible Heating Rate",
                                        Constant::Units::W,
                                        rack.SensZoneCreditHeatRate,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Average,
                                        rack.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Compressor Rack Zone Sensible Heating Energy",
                                        Constant::Units::J,
                                        rack.SensZoneCreditHeat,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Sum,
                                        rack.Name);

                    SetupOutputVariable(state,
                                        "Refrigeration Compressor Rack Return Air Sensible Heating Rate",
                                        Constant::Units::W,
                                        rack.SensHVACCreditHeatRate,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Average,
                                        rack.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Compressor Rack Return Air Sensible Heating Energy",
                                        Constant::Units::J,
                                        rack.SensHVACCreditHeat,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Sum,
                                        rack.Name);

                    // if Location is Zone, GetRefrigerationInputEither checks that you have at least one load and that either:
                    // * You have only cases, and they must be all in the same zone
                    // * Or you must have a Heat Rejection Zone provided
                    int rackZoneNum = -1;
                    if (rack.HeatRejectionZoneNum > 0) {
                        rackZoneNum = rack.HeatRejectionZoneNum;
                    } else {
                        rackZoneNum = RefrigCase(rack.CaseNum(1)).ActualZoneNum;
                    }
                    SetupZoneInternalGain(state,
                                          rackZoneNum,
                                          rack.Name,
                                          DataHeatBalance::IntGainType::RefrigerationCompressorRack,
                                          &rack.SensZoneCreditHeatRate,
                                          &rack.SensHVACCreditHeatRate);

                } // location zone
            } // Serves coils or case/walkin loads

            if (rack.CondenserType == DataHeatBalance::RefrigCondenserType::Water) { // on HVAC time step no matter what
                SetupOutputVariable(state,
                                    "Refrigeration Compressor Rack Condenser Mass Flow Rate",
                                    Constant::Units::kg_s,
                                    rack.MassFlowRate,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Average,
                                    rack.Name);

                SetupOutputVariable(state,
                                    "Refrigeration Compressor Rack Condenser Heat Transfer Rate",
                                    Constant::Units::W,
                                    rack.CondLoad,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Average,
                                    rack.Name);

                SetupOutputVariable(state,
                                    "Refrigeration Compressor Rack Condenser Heat Transfer Energy",
                                    Constant::Units::J,
                                    rack.CondEnergy,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Sum,
                                    rack.Name,
                                    Constant::eResource::EnergyTransfer,
                                    OutputProcessor::Group::Plant,
                                    OutputProcessor::EndUseCat::Heating);

            } // Condenser cooling water
        } // Refrigerated Racks
    } // NumRefrigeratedRacks > 0

    if (state.dataRefrigCase->NumRefrigSystems > 0) {
        // CurrentModuleObject='Refrigeration:System'
        for (int refrigSysNum = 1; refrigSysNum <= state.dataRefrigCase->NumRefrigSystems; ++refrigSysNum) {
            auto &sys = System(refrigSysNum);
            if (sys.CoilFlag) { // system serves chillers and is solved on HVAC time step
                if (sys.NumStages == 1) {
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller System Total Compressor Electricity Rate",
                                        Constant::Units::W,
                                        sys.TotCompPower,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Average,
                                        sys.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller System Total Compressor Electricity Energy",
                                        Constant::Units::J,
                                        sys.TotCompElecConsump,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Sum,
                                        sys.Name);
                } else if (sys.NumStages == 2) {
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller System Total Low Stage Compressor Electricity Rate",
                                        Constant::Units::W,
                                        sys.TotCompPower,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Average,
                                        sys.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller System Total Low Stage Compressor Electricity Energy",
                                        Constant::Units::J,
                                        sys.TotCompElecConsump,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Sum,
                                        sys.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller System Total High Stage Compressor Electricity Rate",
                                        Constant::Units::W,
                                        sys.TotHiStageCompPower,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Average,
                                        sys.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller System Total High Stage Compressor Electricity Energy",
                                        Constant::Units::J,
                                        sys.TotHiStageCompElecConsump,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Sum,
                                        sys.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller System Total Low and High Stage Compressor Electricity Energy",
                                        Constant::Units::J,
                                        sys.TotCompElecConsumpTwoStage,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Sum,
                                        sys.Name);
                } // NumStages
                SetupOutputVariable(state,
                                    "Refrigeration Air Chiller System Average Compressor COP",
                                    Constant::Units::W_W,
                                    sys.AverageCompressorCOP,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Average,
                                    sys.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Air Chiller System Total Air Chiller Heat Transfer Rate",
                                    Constant::Units::W,
                                    sys.TotalCoolingLoad,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Average,
                                    sys.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Air Chiller System Total Case and Walk In Heat Transfer Energy",
                                    Constant::Units::J,
                                    sys.TotalCoolingEnergy,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Sum,
                                    sys.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Air Chiller System Total Transferred Load Heat Transfer Rate",
                                    Constant::Units::W,
                                    sys.TotTransferLoad,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Average,
                                    sys.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Air Chiller System Total Transferred Load Heat Transfer Energy",
                                    Constant::Units::J,
                                    sys.TotTransferEnergy,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Sum,
                                    sys.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Air Chiller System Total Suction Pipe Heat Gain Rate",
                                    Constant::Units::W,
                                    sys.PipeHeatLoad,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Average,
                                    sys.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Air Chiller System Total Suction Pipe Heat Gain Energy",
                                    Constant::Units::J,
                                    sys.PipeHeatEnergy,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Sum,
                                    sys.Name);
                if (sys.NumStages == 1) {
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller System Total Compressor Heat Transfer Rate",
                                        Constant::Units::W,
                                        sys.TotCompCapacity,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Average,
                                        sys.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller System Total Compressor Heat Transfer Energy",
                                        Constant::Units::J,
                                        sys.TotCompCoolingEnergy,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Sum,
                                        sys.Name); // indiv compressors go to meter, not system sum
                } else if (sys.NumStages == 2) {
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller System Total Low Stage Compressor Heat Transfer Rate",
                                        Constant::Units::W,
                                        sys.TotCompCapacity,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Average,
                                        sys.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller System Total Low Stage Compressor Heat Transfer Energy",
                                        Constant::Units::J,
                                        sys.TotCompCoolingEnergy,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Sum,
                                        sys.Name); // indiv compressors go to meter, not system sum
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller System Total High Stage Compressor Heat Transfer Rate",
                                        Constant::Units::W,
                                        sys.TotHiStageCompCapacity,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Average,
                                        sys.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller System Total High Stage Compressor Heat Transfer Energy",
                                        Constant::Units::J,
                                        sys.TotHiStageCompCoolingEnergy,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Sum,
                                        sys.Name); // indiv compressors go to meter, not system sum
                } // NumStages
                SetupOutputVariable(state,
                                    "Refrigeration Air Chiller System Net Rejected Heat Transfer Rate",
                                    Constant::Units::W,
                                    sys.NetHeatRejectLoad,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Average,
                                    sys.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Air Chiller System Net Rejected Heat Transfer Energy",
                                    Constant::Units::J,
                                    sys.NetHeatRejectEnergy,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Sum,
                                    sys.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Air Chiller System Estimated Refrigerant Inventory Mass",
                                    Constant::Units::kg,
                                    sys.RefInventory,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Average,
                                    sys.Name);
                if (sys.NumStages == 1) {
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller System Estimated Refrigerant Mass Flow Rate",
                                        Constant::Units::kg_s,
                                        sys.RefMassFlowComps,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Average,
                                        sys.Name);
                } else if (sys.NumStages == 2) {
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller System Estimated Low Stage Refrigerant Mass Flow Rate",
                                        Constant::Units::kg_s,
                                        sys.RefMassFlowComps,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Average,
                                        sys.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller System Estimated High Stage Refrigerant Mass Flow Rate",
                                        Constant::Units::kg_s,
                                        sys.RefMassFlowHiStageComps,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Average,
                                        sys.Name);
                } // NumStages
                if (sys.NumStages == 2) {
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller System Intercooler Temperature",
                                        Constant::Units::C,
                                        sys.TIntercooler,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Average,
                                        sys.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller System Intercooler Pressure",
                                        Constant::Units::Pa,
                                        sys.PIntercooler,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Average,
                                        sys.Name);
                }
                SetupOutputVariable(state,
                                    "Refrigeration Air Chiller System Condensing Temperature",
                                    Constant::Units::C,
                                    sys.TCondense,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Average,
                                    sys.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Air Chiller System Evaporating Temperature",
                                    Constant::Units::C,
                                    sys.TEvapNeeded,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Average,
                                    sys.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Air Chiller System Suction Temperature",
                                    Constant::Units::C,
                                    sys.TCompIn,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Average,
                                    sys.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Air Chiller System TXV Liquid Temperature",
                                    Constant::Units::C,
                                    sys.TLiqInActual,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Average,
                                    sys.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Air Chiller System Liquid Suction Subcooler Heat Transfer Rate",
                                    Constant::Units::W,
                                    sys.LSHXTrans,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Average,
                                    sys.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Air Chiller System Liquid Suction Subcooler Heat Transfer Energy",
                                    Constant::Units::J,
                                    sys.LSHXTransEnergy,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Sum,
                                    sys.Name);
            } else { // NOT System(SysNum)%CoilFlag, so serving loads on zone timestep
                if (sys.NumStages == 1) {
                    SetupOutputVariable(state,
                                        "Refrigeration System Total Compressor Electricity Rate",
                                        Constant::Units::W,
                                        sys.TotCompPower,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Average,
                                        sys.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration System Total Compressor Electricity Energy",
                                        Constant::Units::J,
                                        sys.TotCompElecConsump,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Sum,
                                        sys.Name);
                } else if (sys.NumStages == 2) {
                    SetupOutputVariable(state,
                                        "Refrigeration System Total Low Stage Compressor Electricity Rate",
                                        Constant::Units::W,
                                        sys.TotCompPower,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Average,
                                        sys.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration System Total Low Stage Compressor Electricity Energy",
                                        Constant::Units::J,
                                        sys.TotCompElecConsump,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Sum,
                                        sys.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration System Total High Stage Compressor Electricity Rate",
                                        Constant::Units::W,
                                        sys.TotHiStageCompPower,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Average,
                                        sys.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration System Total High Stage Compressor Electricity Energy",
                                        Constant::Units::J,
                                        sys.TotHiStageCompElecConsump,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Sum,
                                        sys.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration System Total Low and High Stage Compressor Electricity Energy",
                                        Constant::Units::J,
                                        sys.TotCompElecConsumpTwoStage,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Sum,
                                        sys.Name);
                } // NumStages
                SetupOutputVariable(state,
                                    "Refrigeration System Average Compressor COP",
                                    Constant::Units::W_W,
                                    sys.AverageCompressorCOP,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Average,
                                    sys.Name);
                SetupOutputVariable(state,
                                    "Refrigeration System Total Cases and Walk Ins Heat Transfer Rate",
                                    Constant::Units::W,
                                    sys.TotalCoolingLoad,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Average,
                                    sys.Name);
                SetupOutputVariable(state,
                                    "Refrigeration System Total Cases and Walk Ins Heat Transfer Energy",
                                    Constant::Units::J,
                                    sys.TotalCoolingEnergy,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Sum,
                                    sys.Name);
                SetupOutputVariable(state,
                                    "Refrigeration System Total Transferred Load Heat Transfer Rate",
                                    Constant::Units::W,
                                    sys.TotTransferLoad,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Average,
                                    sys.Name);
                SetupOutputVariable(state,
                                    "Refrigeration System Total Transferred Load Heat Transfer Energy",
                                    Constant::Units::J,
                                    sys.TotTransferEnergy,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Sum,
                                    sys.Name);
                SetupOutputVariable(state,
                                    "Refrigeration System Total Suction Pipe Heat Gain Rate",
                                    Constant::Units::W,
                                    sys.PipeHeatLoad,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Average,
                                    sys.Name);
                SetupOutputVariable(state,
                                    "Refrigeration System Total Suction Pipe Heat Gain Energy",
                                    Constant::Units::J,
                                    sys.PipeHeatEnergy,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Sum,
                                    sys.Name);
                if (sys.NumStages == 1) {
                    SetupOutputVariable(state,
                                        "Refrigeration System Total Compressor Heat Transfer Rate",
                                        Constant::Units::W,
                                        sys.TotCompCapacity,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Average,
                                        sys.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration System Total Compressor Heat Transfer Energy",
                                        Constant::Units::J,
                                        sys.TotCompCoolingEnergy,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Sum,
                                        sys.Name); // indiv compressors go to meter, not system sum
                } else if (sys.NumStages == 2) {
                    SetupOutputVariable(state,
                                        "Refrigeration System Total Low Stage Compressor Heat Transfer Rate",
                                        Constant::Units::W,
                                        sys.TotCompCapacity,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Average,
                                        sys.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration System Total Low Stage Compressor Heat Transfer Energy",
                                        Constant::Units::J,
                                        sys.TotCompCoolingEnergy,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Sum,
                                        sys.Name); // indiv compressors go to meter, not system sum
                    SetupOutputVariable(state,
                                        "Refrigeration System Total High Stage Compressor Heat Transfer Rate",
                                        Constant::Units::W,
                                        sys.TotHiStageCompCapacity,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Average,
                                        sys.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration System Total High Stage Compressor Heat Transfer Energy",
                                        Constant::Units::J,
                                        sys.TotHiStageCompCoolingEnergy,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Sum,
                                        sys.Name); // indiv compressors go to meter, not system sum
                } // NumStages
                SetupOutputVariable(state,
                                    "Refrigeration System Net Rejected Heat Transfer Rate",
                                    Constant::Units::W,
                                    sys.NetHeatRejectLoad,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Average,
                                    sys.Name);
                SetupOutputVariable(state,
                                    "Refrigeration System Net Rejected Heat Transfer Energy",
                                    Constant::Units::J,
                                    sys.NetHeatRejectEnergy,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Sum,
                                    sys.Name);
                SetupOutputVariable(state,
                                    "Refrigeration System Estimated Refrigerant Inventory Mass",
                                    Constant::Units::kg,
                                    sys.RefInventory,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Average,
                                    sys.Name);
                if (sys.NumStages == 1) {
                    SetupOutputVariable(state,
                                        "Refrigeration System Estimated Refrigerant Mass Flow Rate",
                                        Constant::Units::kg_s,
                                        sys.RefMassFlowComps,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Average,
                                        sys.Name);
                } else if (sys.NumStages == 2) {
                    SetupOutputVariable(state,
                                        "Refrigeration System Estimated Low Stage Refrigerant Mass Flow Rate",
                                        Constant::Units::kg_s,
                                        sys.RefMassFlowComps,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Average,
                                        sys.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration System Estimated High Stage Refrigerant Mass Flow Rate",
                                        Constant::Units::kg_s,
                                        sys.RefMassFlowHiStageComps,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Average,
                                        sys.Name);
                } // NumStages
                if (sys.NumStages == 2) {
                    SetupOutputVariable(state,
                                        "Refrigeration System Intercooler Temperature",
                                        Constant::Units::C,
                                        sys.TIntercooler,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Average,
                                        sys.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration System Intercooler Pressure",
                                        Constant::Units::Pa,
                                        sys.PIntercooler,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Average,
                                        sys.Name);
                }
                SetupOutputVariable(state,
                                    "Refrigeration System Condensing Temperature",
                                    Constant::Units::C,
                                    sys.TCondense,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Average,
                                    sys.Name);
                SetupOutputVariable(state,
                                    "Refrigeration System Evaporating Temperature",
                                    Constant::Units::C,
                                    sys.TEvapNeeded,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Average,
                                    sys.Name);
                SetupOutputVariable(state,
                                    "Refrigeration System Suction Pipe Suction Temperature",
                                    Constant::Units::C,
                                    sys.TCompIn,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Average,
                                    sys.Name);
                SetupOutputVariable(state,
                                    "Refrigeration System Thermostatic Expansion Valve Liquid Temperature",
                                    Constant::Units::C,
                                    sys.TLiqInActual,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Average,
                                    sys.Name);
                SetupOutputVariable(state,
                                    "Refrigeration System Liquid Suction Subcooler Heat Transfer Rate",
                                    Constant::Units::W,
                                    sys.LSHXTrans,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Average,
                                    sys.Name);
                SetupOutputVariable(state,
                                    "Refrigeration System Liquid Suction Subcooler Heat Transfer Energy",
                                    Constant::Units::J,
                                    sys.LSHXTransEnergy,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Sum,
                                    sys.Name);
            } // System(coilflag)

            if (sys.SystemRejectHeatToZone) {
                if (Condenser(sys.CondenserNum(1)).InletAirZoneNum > 0) {
                    SetupZoneInternalGain(state,
                                          Condenser(sys.CondenserNum(1)).InletAirZoneNum,
                                          sys.Name,
                                          DataHeatBalance::IntGainType::RefrigerationSystemAirCooledCondenser,
                                          &sys.NetHeatRejectLoad);
                }

                if (sys.SuctionPipeActualZoneNum > 0) {
                    SetupZoneInternalGain(state,
                                          sys.SuctionPipeActualZoneNum,
                                          sys.Name,
                                          DataHeatBalance::IntGainType::RefrigerationSystemSuctionPipe,
                                          &sys.PipeHeatLoad);
                }
            }
        } // numrefrigsystems

        // Report Compressor ENERGY here, not on system level for meters.
        for (int compNum = 1; compNum <= state.dataRefrigCase->NumSimulationCompressors; ++compNum) {
            auto &comp = Compressor(compNum);
            // CurrentModuleObject='Refrigeration:Compressor'
            if (comp.NumSysAttach == 1) { // only set up reports for compressors that are used once and only once
                if (comp.CoilFlag) {      // Compressor serving system with chillers on HVAC time step
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller System Compressor Electricity Rate",
                                        Constant::Units::W,
                                        comp.Power,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Average,
                                        comp.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller System Compressor Electricity Energy",
                                        Constant::Units::J,
                                        comp.ElecConsumption,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Sum,
                                        comp.Name,
                                        Constant::eResource::Electricity,
                                        OutputProcessor::Group::Plant,
                                        OutputProcessor::EndUseCat::Refrigeration,
                                        comp.EndUseSubcategory);
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller System Compressor Heat Transfer Rate",
                                        Constant::Units::W,
                                        comp.Capacity,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Average,
                                        comp.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller System Compressor Heat Transfer Energy",
                                        Constant::Units::J,
                                        comp.CoolingEnergy,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Sum,
                                        comp.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller System Compressor Runtime Fraction",
                                        Constant::Units::None,
                                        comp.LoadFactor,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Average,
                                        comp.Name);
                } else { // serve cases/walkins on zone time step
                    SetupOutputVariable(state,
                                        "Refrigeration Compressor Electricity Rate",
                                        Constant::Units::W,
                                        comp.Power,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Average,
                                        comp.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Compressor Electricity Energy",
                                        Constant::Units::J,
                                        comp.ElecConsumption,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Sum,
                                        comp.Name,
                                        Constant::eResource::Electricity,
                                        OutputProcessor::Group::Plant,
                                        OutputProcessor::EndUseCat::Refrigeration,
                                        comp.EndUseSubcategory);
                    SetupOutputVariable(state,
                                        "Refrigeration Compressor Heat Transfer Rate",
                                        Constant::Units::W,
                                        comp.Capacity,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Average,
                                        comp.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Compressor Heat Transfer Energy",
                                        Constant::Units::J,
                                        comp.CoolingEnergy,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Sum,
                                        comp.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Compressor Runtime Fraction",
                                        Constant::Units::None,
                                        comp.LoadFactor,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Average,
                                        comp.Name);
                } // Serve coils on HVAC time step or cases/walkins on Zone time step
            } // NumSysAttach
        } // CompNum on NumSimulationCompressors

        // Report Variables for Refrigeration Condensers
        for (int condNum = 1; condNum <= state.dataRefrigCase->NumRefrigCondensers; ++condNum) {
            auto &cond = Condenser(condNum);
            // CurrentModuleObject='Refrigeration:Condenser:*'
            if (cond.CoilFlag) { // Condenser serving system with chillers on HVAC time step
                SetupOutputVariable(state,
                                    "Refrigeration Air Chiller System Condenser Heat Transfer Rate",
                                    Constant::Units::W,
                                    cond.CondLoad,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Average,
                                    cond.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Air Chiller System Condenser Heat Transfer Energy",
                                    Constant::Units::J,
                                    cond.CondEnergy,
                                    OutputProcessor::TimeStepType::System,
                                    OutputProcessor::StoreType::Sum,
                                    cond.Name);

                if (cond.CondenserType != DataHeatBalance::RefrigCondenserType::Cascade) {
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller System Condenser Total Recovered Heat Transfer Rate",
                                        Constant::Units::W,
                                        cond.TotalHeatRecoveredLoad,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Average,
                                        cond.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller System Condenser Total Recovered Heat Transfer Energy",
                                        Constant::Units::J,
                                        cond.TotalHeatRecoveredEnergy,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Sum,
                                        cond.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller System Condenser Non Refrigeration Recovered Heat Transfer Rate",
                                        Constant::Units::W,
                                        cond.ExternalHeatRecoveredLoad,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Average,
                                        cond.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller System Condenser Non Refrigeration Recovered Heat Transfer Energy",
                                        Constant::Units::J,
                                        cond.ExternalEnergyRecovered,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Sum,
                                        cond.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller System Condenser Defrost Recovered Heat Transfer Rate",
                                        Constant::Units::W,
                                        cond.InternalHeatRecoveredLoad,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Average,
                                        cond.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller System Condenser Defrost Recovered Heat Transfer Energy",
                                        Constant::Units::J,
                                        cond.InternalEnergyRecovered,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Sum,
                                        cond.Name);
                } // not cascade because recovered energy on cascade systems passed up to higher temperature system

                if (cond.CondenserType == DataHeatBalance::RefrigCondenserType::Air) {
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller System Condenser Fan Electricity Rate",
                                        Constant::Units::W,
                                        cond.ActualFanPower,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Average,
                                        cond.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller System Condenser Fan Electricity Energy",
                                        Constant::Units::J,
                                        cond.FanElecEnergy,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Sum,
                                        cond.Name,
                                        Constant::eResource::Electricity,
                                        OutputProcessor::Group::Plant,
                                        OutputProcessor::EndUseCat::Refrigeration,
                                        cond.EndUseSubcategory);
                } // Air cooled

                if (cond.CondenserType == DataHeatBalance::RefrigCondenserType::Evap) {
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller System Condenser Fan Electricity Rate",
                                        Constant::Units::W,
                                        cond.ActualFanPower,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Average,
                                        cond.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller System Condenser Fan Electricity Energy",
                                        Constant::Units::J,
                                        cond.FanElecEnergy,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Sum,
                                        cond.Name,
                                        Constant::eResource::Electricity,
                                        OutputProcessor::Group::Plant,
                                        OutputProcessor::EndUseCat::Refrigeration,
                                        cond.EndUseSubcategory);
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller System Condenser Pump Electricity Rate",
                                        Constant::Units::W,
                                        cond.ActualEvapPumpPower,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Average,
                                        cond.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller System Condenser Pump Electricity Energy",
                                        Constant::Units::J,
                                        cond.EvapPumpConsumption,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Sum,
                                        cond.Name,
                                        Constant::eResource::Electricity,
                                        OutputProcessor::Group::Plant,
                                        OutputProcessor::EndUseCat::Refrigeration,
                                        cond.EndUseSubcategory);
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller System Condenser Basin Heater Electricity Rate",
                                        Constant::Units::W,
                                        cond.BasinHeaterPower,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Average,
                                        cond.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller System Condenser Basin Heater Electricity Energy",
                                        Constant::Units::J,
                                        cond.BasinHeaterConsumption,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Sum,
                                        cond.Name,
                                        Constant::eResource::Electricity,
                                        OutputProcessor::Group::Plant,
                                        OutputProcessor::EndUseCat::Refrigeration,
                                        cond.EndUseSubcategory);
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller System Condenser Evaporated Water Volume Flow Rate",
                                        Constant::Units::m3_s,
                                        cond.EvapWaterConsumpRate,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Average,
                                        cond.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller System Condenser Evaporated Water Volume",
                                        Constant::Units::m3,
                                        cond.EvapWaterConsumption,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Sum,
                                        cond.Name,
                                        Constant::eResource::Water,
                                        OutputProcessor::Group::Plant,
                                        OutputProcessor::EndUseCat::Refrigeration,
                                        cond.EndUseSubcategory);
                } // Evaporative Condenser Variables

                if (cond.CondenserType == DataHeatBalance::RefrigCondenserType::Water) {
                    SetupOutputVariable(state,
                                        "Refrigeration Air Chiller System Condenser Fluid Mass Flow Rate",
                                        Constant::Units::kg_s,
                                        cond.MassFlowRate,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Average,
                                        cond.Name);

                } // Water-cooled Condenser variables

            } else { // Serving loads/systems with cases and walkins on zone time step

                SetupOutputVariable(state,
                                    "Refrigeration System Condenser Heat Transfer Rate",
                                    Constant::Units::W,
                                    cond.CondLoad,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Average,
                                    cond.Name);
                SetupOutputVariable(state,
                                    "Refrigeration System Condenser Heat Transfer Energy",
                                    Constant::Units::J,
                                    cond.CondEnergy,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Sum,
                                    cond.Name);

                if (cond.CondenserType != DataHeatBalance::RefrigCondenserType::Cascade) {
                    SetupOutputVariable(state,
                                        "Refrigeration System Condenser Total Recovered Heat Transfer Rate",
                                        Constant::Units::W,
                                        cond.TotalHeatRecoveredLoad,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Average,
                                        cond.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration System Condenser Total Recovered Heat Transfer Energy",
                                        Constant::Units::J,
                                        cond.TotalHeatRecoveredEnergy,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Sum,
                                        cond.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration System Condenser Non Refrigeration Recovered Heat Transfer Rate",
                                        Constant::Units::W,
                                        cond.ExternalHeatRecoveredLoad,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Average,
                                        cond.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration System Condenser Non Refrigeration Recovered Heat Transfer Energy",
                                        Constant::Units::J,
                                        cond.ExternalEnergyRecovered,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Sum,
                                        cond.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration System Condenser Defrost Recovered Heat Transfer Rate",
                                        Constant::Units::W,
                                        cond.InternalHeatRecoveredLoad,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Average,
                                        cond.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration System Condenser Defrost Recovered Heat Transfer Energy",
                                        Constant::Units::J,
                                        cond.InternalEnergyRecovered,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Sum,
                                        cond.Name);
                } // not cascade because recovered energy on cascade systems passed up to higher temperature system

                if (cond.CondenserType == DataHeatBalance::RefrigCondenserType::Air) {
                    SetupOutputVariable(state,
                                        "Refrigeration System Condenser Fan Electricity Rate",
                                        Constant::Units::W,
                                        cond.ActualFanPower,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Average,
                                        cond.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration System Condenser Fan Electricity Energy",
                                        Constant::Units::J,
                                        cond.FanElecEnergy,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Sum,
                                        cond.Name,
                                        Constant::eResource::Electricity,
                                        OutputProcessor::Group::Plant,
                                        OutputProcessor::EndUseCat::Refrigeration,
                                        cond.EndUseSubcategory);
                } // Air cooled

                if (cond.CondenserType == DataHeatBalance::RefrigCondenserType::Evap) {
                    SetupOutputVariable(state,
                                        "Refrigeration System Condenser Fan Electricity Rate",
                                        Constant::Units::W,
                                        cond.ActualFanPower,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Average,
                                        cond.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration System Condenser Fan Electricity Energy",
                                        Constant::Units::J,
                                        cond.FanElecEnergy,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Sum,
                                        cond.Name,
                                        Constant::eResource::Electricity,
                                        OutputProcessor::Group::Plant,
                                        OutputProcessor::EndUseCat::Refrigeration,
                                        cond.EndUseSubcategory);
                    SetupOutputVariable(state,
                                        "Refrigeration System Condenser Pump Electricity Rate",
                                        Constant::Units::W,
                                        cond.ActualEvapPumpPower,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Average,
                                        cond.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration System Condenser Pump Electricity Energy",
                                        Constant::Units::J,
                                        cond.EvapPumpConsumption,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Sum,
                                        cond.Name,
                                        Constant::eResource::Electricity,
                                        OutputProcessor::Group::Plant,
                                        OutputProcessor::EndUseCat::Refrigeration,
                                        cond.EndUseSubcategory);
                    SetupOutputVariable(state,
                                        "Refrigeration System Condenser Basin Heater Electricity Rate",
                                        Constant::Units::W,
                                        cond.BasinHeaterPower,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Average,
                                        cond.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration System Condenser Basin Heater Electricity Energy",
                                        Constant::Units::J,
                                        cond.BasinHeaterConsumption,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Sum,
                                        cond.Name,
                                        Constant::eResource::Electricity,
                                        OutputProcessor::Group::Plant,
                                        OutputProcessor::EndUseCat::Refrigeration,
                                        cond.EndUseSubcategory);
                    SetupOutputVariable(state,
                                        "Refrigeration System Condenser Evaporated Water Volume Flow Rate",
                                        Constant::Units::m3_s,
                                        cond.EvapWaterConsumpRate,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Average,
                                        cond.Name);
                    SetupOutputVariable(state,
                                        "Refrigeration System Condenser Evaporated Water Volume",
                                        Constant::Units::m3,
                                        cond.EvapWaterConsumption,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Sum,
                                        cond.Name,
                                        Constant::eResource::Water,
                                        OutputProcessor::Group::Plant,
                                        OutputProcessor::EndUseCat::Refrigeration,
                                        cond.EndUseSubcategory);
                } // Evaporative Condenser Variables

                if (cond.CondenserType == DataHeatBalance::RefrigCondenserType::Water) {
                    SetupOutputVariable(state,
                                        "Refrigeration System Condenser Water Mass Flow Rate",
                                        Constant::Units::kg_s,
                                        cond.MassFlowRate,
                                        OutputProcessor::TimeStepType::System,
                                        OutputProcessor::StoreType::Average,
                                        cond.Name);

                } // Water-cooled Condenser variables
            } // Condenser%CoilFlag to distinguish HVAC vs Zone time steps
        } // CondNum on DataHeatBalance::NumRefrigCondensers

        if (state.dataRefrigCase->NumSimulationSubcoolers > 0) {
            for (int subcoolNum = 1; subcoolNum <= state.dataRefrigCase->NumSimulationSubcoolers; ++subcoolNum) {
                auto &cooler = Subcooler(subcoolNum);
                // CurrentModuleObject='Refrigeration:Subcooler'
                if (cooler.CoilFlag) { // Subcooler serving system with chillers on HVAC time step
                    if (cooler.subcoolerType == SubcoolerType::Mechanical) {
                        SetupOutputVariable(state,
                                            "Refrigeration Air Chiller System Mechanical Subcooler Heat Transfer Rate",
                                            Constant::Units::W,
                                            cooler.MechSCTransLoad,
                                            OutputProcessor::TimeStepType::Zone,
                                            OutputProcessor::StoreType::Average,
                                            cooler.Name);
                        SetupOutputVariable(state,
                                            "Refrigeration Air Chiller System Mechanical Subcooler Heat Transfer Energy",
                                            Constant::Units::J,
                                            cooler.MechSCTransEnergy,
                                            OutputProcessor::TimeStepType::Zone,
                                            OutputProcessor::StoreType::Sum,
                                            cooler.Name);
                    }
                } else { // Subcooler on system serving cases and/or walkins
                    if (cooler.subcoolerType == SubcoolerType::Mechanical) {
                        SetupOutputVariable(state,
                                            "Refrigeration System Mechanical Subcooler Heat Transfer Rate",
                                            Constant::Units::W,
                                            cooler.MechSCTransLoad,
                                            OutputProcessor::TimeStepType::System,
                                            OutputProcessor::StoreType::Average,
                                            cooler.Name);
                        SetupOutputVariable(state,
                                            "Refrigeration System Mechanical Subcooler Heat Transfer Energy",
                                            Constant::Units::J,
                                            cooler.MechSCTransEnergy,
                                            OutputProcessor::TimeStepType::System,
                                            OutputProcessor::StoreType::Sum,
                                            cooler.Name);
                    }
                } // Subcoolers on system serving chillers
            } // Subcoolnum on NumSimulationSubcoolers
        } // NumSimulationSubcoolers > 0

    } // NumRefrigSystems > 0

    if (state.dataRefrigCase->NumTransRefrigSystems > 0) {
        // CurrentModuleObject='Refrigeration:TranscriticalSystem'
        for (int refrigSysNum = 1; refrigSysNum <= state.dataRefrigCase->NumTransRefrigSystems; ++refrigSysNum) {
            auto &sys = TransSystem(refrigSysNum);
            // for both SingleStage and TwoStage systems (medium temperature loads present)
            SetupOutputVariable(state,
                                "Refrigeration Transcritical System Total High Pressure Compressor Electricity Rate",
                                Constant::Units::W,
                                sys.TotCompPowerHP,
                                OutputProcessor::TimeStepType::Zone,
                                OutputProcessor::StoreType::Average,
                                sys.Name);
            SetupOutputVariable(state,
                                "Refrigeration Transcritical System Total High Pressure Compressor Electricity Energy",
                                Constant::Units::J,
                                sys.TotCompElecConsumpHP,
                                OutputProcessor::TimeStepType::Zone,
                                OutputProcessor::StoreType::Sum,
                                sys.Name);
            SetupOutputVariable(state,
                                "Refrigeration Transcritical System Total Compressor Electricity Energy",
                                Constant::Units::J,
                                sys.TotCompElecConsump,
                                OutputProcessor::TimeStepType::Zone,
                                OutputProcessor::StoreType::Sum,
                                sys.Name);
            SetupOutputVariable(state,
                                "Refrigeration Transcritical System Average COP",
                                Constant::Units::W_W,
                                sys.AverageCompressorCOP,
                                OutputProcessor::TimeStepType::Zone,
                                OutputProcessor::StoreType::Average,
                                sys.Name);
            SetupOutputVariable(state,
                                "Refrigeration Transcritical System Medium Temperature Cases and Walk Ins Heat Transfer Rate",
                                Constant::Units::W,
                                sys.TotalCoolingLoadMT,
                                OutputProcessor::TimeStepType::Zone,
                                OutputProcessor::StoreType::Average,
                                sys.Name);
            SetupOutputVariable(state,
                                "Refrigeration Transcritical System Medium Temperature Cases and Walk Ins Heat Transfer Energy",
                                Constant::Units::J,
                                sys.TotalCoolingEnergyMT,
                                OutputProcessor::TimeStepType::Zone,
                                OutputProcessor::StoreType::Sum,
                                sys.Name);
            SetupOutputVariable(state,
                                "Refrigeration Transcritical System Total Cases and Walk Ins Heat Transfer Energy",
                                Constant::Units::J,
                                sys.TotalCoolingEnergy,
                                OutputProcessor::TimeStepType::Zone,
                                OutputProcessor::StoreType::Sum,
                                sys.Name);
            SetupOutputVariable(state,
                                "Refrigeration Transcritical System Medium Temperature Suction Pipe Heat Transfer Rate",
                                Constant::Units::W,
                                sys.PipeHeatLoadMT,
                                OutputProcessor::TimeStepType::Zone,
                                OutputProcessor::StoreType::Average,
                                sys.Name);
            SetupOutputVariable(state,
                                "Refrigeration Transcritical System Medium Temperature Suction Pipe Heat Transfer Energy",
                                Constant::Units::J,
                                sys.PipeHeatEnergyMT,
                                OutputProcessor::TimeStepType::Zone,
                                OutputProcessor::StoreType::Sum,
                                sys.Name);
            SetupOutputVariable(state,
                                "Refrigeration Transcritical System High Pressure Compressor Heat Transfer Rate",
                                Constant::Units::W,
                                sys.TotCompCapacityHP,
                                OutputProcessor::TimeStepType::Zone,
                                OutputProcessor::StoreType::Average,
                                sys.Name);
            SetupOutputVariable(state,
                                "Refrigeration Transcritical System High Pressure Compressor Heat Transfer Energy",
                                Constant::Units::J,
                                sys.TotCompCoolingEnergyHP,
                                OutputProcessor::TimeStepType::Zone,
                                OutputProcessor::StoreType::Sum,
                                sys.Name); // indiv compressors go to meter, not system sum
            SetupOutputVariable(state,
                                "Refrigeration Transcritical System Net Rejected Heat Transfer Rate",
                                Constant::Units::W,
                                sys.NetHeatRejectLoad,
                                OutputProcessor::TimeStepType::Zone,
                                OutputProcessor::StoreType::Average,
                                sys.Name);
            SetupOutputVariable(state,
                                "Refrigeration Transcritical System Net Rejected Heat Transfer Energy",
                                Constant::Units::J,
                                sys.NetHeatRejectEnergy,
                                OutputProcessor::TimeStepType::Zone,
                                OutputProcessor::StoreType::Sum,
                                sys.Name);
            SetupOutputVariable(state,
                                "Refrigeration Transcritical System Estimated Refrigerant Inventory Mass",
                                Constant::Units::kg,
                                sys.RefInventory,
                                OutputProcessor::TimeStepType::Zone,
                                OutputProcessor::StoreType::Average,
                                sys.Name);
            SetupOutputVariable(state,
                                "Refrigeration Transcritical System Refrigerant Mass Flow Rate",
                                Constant::Units::kg_s,
                                sys.RefMassFlowComps,
                                OutputProcessor::TimeStepType::Zone,
                                OutputProcessor::StoreType::Average,
                                sys.Name);
            SetupOutputVariable(state,
                                "Refrigeration Transcritical System Medium Temperature Evaporating Temperature",
                                Constant::Units::C,
                                sys.TEvapNeededMT,
                                OutputProcessor::TimeStepType::Zone,
                                OutputProcessor::StoreType::Average,
                                sys.Name);
            SetupOutputVariable(state,
                                "Refrigeration Transcritical System Medium Temperature Suction Temperature",
                                Constant::Units::C,
                                sys.TCompInHP,
                                OutputProcessor::TimeStepType::Zone,
                                OutputProcessor::StoreType::Average,
                                sys.Name);
            if (sys.transSysType == TransSysType::TwoStage) { // for TwoStage system only (low temperature loads present)
                SetupOutputVariable(state,
                                    "Refrigeration Transcritical System Low Pressure Compressor Electricity Rate",
                                    Constant::Units::W,
                                    sys.TotCompPowerLP,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Average,
                                    sys.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Transcritical System Low Pressure Compressor Electricity Energy",
                                    Constant::Units::J,
                                    sys.TotCompElecConsumpLP,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Sum,
                                    sys.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Transcritical System Low Temperature Cases and Walk Ins Heat Transfer Rate",
                                    Constant::Units::W,
                                    sys.TotalCoolingLoadLT,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Average,
                                    sys.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Transcritical System Low Temperature Cases and Walk Ins Heat Transfer Energy",
                                    Constant::Units::J,
                                    sys.TotalCoolingEnergyLT,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Sum,
                                    sys.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Transcritical System Low Temperature Suction Pipe Heat Transfer Rate",
                                    Constant::Units::W,
                                    sys.PipeHeatLoadLT,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Average,
                                    sys.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Transcritical System Low Temperature Suction Pipe Heat Transfer Energy",
                                    Constant::Units::J,
                                    sys.PipeHeatEnergyLT,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Sum,
                                    sys.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Transcritical System Low Pressure Compressor Heat Transfer Rate",
                                    Constant::Units::W,
                                    sys.TotCompCapacityLP,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Average,
                                    sys.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Transcritical System Low Pressure Compressor Heat Transfer Energy",
                                    Constant::Units::J,
                                    sys.TotCompCoolingEnergyLP,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Sum,
                                    sys.Name); // indiv compressors go to meter, not system sum
                SetupOutputVariable(state,
                                    "Refrigeration Transcritical System Low Temperature Evaporating Temperature",
                                    Constant::Units::C,
                                    sys.TEvapNeededLT,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Average,
                                    sys.Name);
                SetupOutputVariable(state,
                                    "Refrigeration Transcritical System Low Temperature Suction Temperature",
                                    Constant::Units::C,
                                    sys.TCompInLP,
                                    OutputProcessor::TimeStepType::Zone,
                                    OutputProcessor::StoreType::Average,
                                    sys.Name);
            } // (sys%TransSysType == 2)

            if (sys.SystemRejectHeatToZone) {
                if (GasCooler(sys.GasCoolerNum(1)).InletAirZoneNum > 0) {
                    SetupZoneInternalGain(state,
                                          GasCooler(sys.GasCoolerNum(1)).InletAirZoneNum,
                                          sys.Name,
                                          DataHeatBalance::IntGainType::RefrigerationTransSysAirCooledGasCooler,
                                          &sys.NetHeatRejectLoad);
                }
            } // (sys%SystemRejectHeatToZone)
            if (sys.SuctionPipeActualZoneNumMT > 0) {
                SetupZoneInternalGain(state,
                                      sys.SuctionPipeActualZoneNumMT,
                                      sys.Name,
                                      DataHeatBalance::IntGainType::RefrigerationTransSysSuctionPipeMT,
                                      &sys.PipeHeatLoadMT);
            } // sys%SuctionPipeActualZoneNumMT > 0
            if (sys.SuctionPipeActualZoneNumLT > 0) {
                SetupZoneInternalGain(state,
                                      sys.SuctionPipeActualZoneNumLT,
                                      sys.Name,
                                      DataHeatBalance::IntGainType::RefrigerationTransSysSuctionPipeLT,
                                      &sys.PipeHeatLoadLT);
            } // sys%SuctionPipeActualZoneNumLT > 0

            // Report Compressor ENERGY here, not on system level for meters.
            // LP compressors
            for (int compIndex = 1; compIndex <= sys.NumCompressorsLP; ++compIndex) {
                int compNum = sys.CompressorNumLP(compIndex);
                // CurrentModuleObject='Refrigeration:Compressor'
                if (Compressor(compNum).NumSysAttach == 1) { // only set up reports for compressors that are used once and only once
                    SetupOutputVariable(state,
                                        "Refrigeration Compressor Electricity Rate",
                                        Constant::Units::W,
                                        Compressor(compNum).Power,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Average,
                                        Compressor(compNum).Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Compressor Electricity Energy",
                                        Constant::Units::J,
                                        Compressor(compNum).ElecConsumption,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Sum,
                                        Compressor(compNum).Name,
                                        Constant::eResource::Electricity,
                                        OutputProcessor::Group::Plant,
                                        OutputProcessor::EndUseCat::Refrigeration,
                                        Compressor(compNum).EndUseSubcategory);
                    SetupOutputVariable(state,
                                        "Refrigeration Compressor Heat Transfer Rate",
                                        Constant::Units::W,
                                        Compressor(compNum).Capacity,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Average,
                                        Compressor(compNum).Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Compressor Heat Transfer Energy",
                                        Constant::Units::J,
                                        Compressor(compNum).CoolingEnergy,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Sum,
                                        Compressor(compNum).Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Compressor Runtime Fraction",
                                        Constant::Units::None,
                                        Compressor(compNum).LoadFactor,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Average,
                                        Compressor(compNum).Name);
                } // NumSysAttach
            } // sys%NumCompressorsLP

            // HP compressors
            for (int compIndex = 1; compIndex <= sys.NumCompressorsHP; ++compIndex) {
                int compNum = sys.CompressorNumHP(compIndex);
                // CurrentModuleObject='Refrigeration:Compressor'
                if (Compressor(compNum).NumSysAttach == 1) { // only set up reports for compressors that are used once and only once
                    SetupOutputVariable(state,
                                        "Refrigeration Compressor Electricity Rate",
                                        Constant::Units::W,
                                        Compressor(compNum).Power,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Average,
                                        Compressor(compNum).Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Compressor Electricity Energy",
                                        Constant::Units::J,
                                        Compressor(compNum).ElecConsumption,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Sum,
                                        Compressor(compNum).Name,
                                        Constant::eResource::Electricity,
                                        OutputProcessor::Group::Plant,
                                        OutputProcessor::EndUseCat::Refrigeration,
                                        Compressor(compNum).EndUseSubcategory);
                    SetupOutputVariable(state,
                                        "Refrigeration Compressor Heat Transfer Rate",
                                        Constant::Units::W,
                                        Compressor(compNum).Capacity,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Average,
                                        Compressor(compNum).Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Compressor Heat Transfer Energy",
                                        Constant::Units::J,
                                        Compressor(compNum).CoolingEnergy,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Sum,
                                        Compressor(compNum).Name);
                    SetupOutputVariable(state,
                                        "Refrigeration Compressor Runtime Fraction",
                                        Constant::Units::None,
                                        Compressor(compNum).LoadFactor,
                                        OutputProcessor::TimeStepType::Zone,
                                        OutputProcessor::StoreType::Average,
                                        Compressor(compNum).Name);
                } // NumSysAttach
            } // sys%NumCompressorsHP

        } // NumTransRefrigSystems
    } // (NumTransRefrigSystems > 0)

    if (state.dataRefrigCase->NumSimulationGasCooler > 0) {
        for (int GCNum = 1; GCNum <= state.dataRefrigCase->NumSimulationGasCooler; ++GCNum) {
            auto &cooler = GasCooler(GCNum);
            // CurrentModuleObject='Refrigeration:GasCooler:AirCooled'
            SetupOutputVariable(state,
                                "Refrigeration Transcritical System Gas Cooler Heat Transfer Rate",
                                Constant::Units::W,
                                cooler.GasCoolerLoad,
                                OutputProcessor::TimeStepType::Zone,
                                OutputProcessor::StoreType::Average,
                                cooler.Name);
            SetupOutputVariable(state,
                                "Refrigeration Transcritical System Gas Cooler Heat Transfer Energy",
                                Constant::Units::J,
                                cooler.GasCoolerEnergy,
                                OutputProcessor::TimeStepType::Zone,
                                OutputProcessor::StoreType::Sum,
                                cooler.Name);
            SetupOutputVariable(state,
                                "Refrigeration Transcritical System Gas Cooler Fan Electricity Rate",
                                Constant::Units::W,
                                cooler.ActualFanPower,
                                OutputProcessor::TimeStepType::Zone,
                                OutputProcessor::StoreType::Average,
                                cooler.Name);
            SetupOutputVariable(state,
                                "Refrigeration Transcritical System Gas Cooler Fan Electricity Energy",
                                Constant::Units::J,
                                cooler.FanElecEnergy,
                                OutputProcessor::TimeStepType::Zone,
                                OutputProcessor::StoreType::Sum,
                                cooler.Name,
                                Constant::eResource::Electricity,
                                OutputProcessor::Group::Plant,
                                OutputProcessor::EndUseCat::Refrigeration,
                                cooler.EndUseSubcategory);
            SetupOutputVariable(state,
                                "Refrigeration Transcritical System Gas Cooler Outlet Temperature",
                                Constant::Units::C,
                                cooler.TGasCoolerOut,
                                OutputProcessor::TimeStepType::Zone,
                                OutputProcessor::StoreType::Average,
                                cooler.Name);
            SetupOutputVariable(state,
                                "Refrigeration Transcritical System Gas Cooler Outlet Pressure",
                                Constant::Units::Pa,
                                cooler.PGasCoolerOut,
                                OutputProcessor::TimeStepType::Zone,
                                OutputProcessor::StoreType::Average,
                                cooler.Name);
            SetupOutputVariable(state,
                                "Refrigeration Transcritical System Gas Cooler Defrost Recovered Heat Transfer Rate",
                                Constant::Units::W,
                                cooler.InternalHeatRecoveredLoad,
                                OutputProcessor::TimeStepType::Zone,
                                OutputProcessor::StoreType::Average,
                                cooler.Name);
            SetupOutputVariable(state,
                                "Refrigeration Transcritical System Gas Cooler Defrost Recovered Heat Transfer Energy",
                                Constant::Units::J,
                                cooler.InternalEnergyRecovered,
                                OutputProcessor::TimeStepType::Zone,
                                OutputProcessor::StoreType::Sum,
                                cooler.Name);
        } // GCNum on NumSimulationGasCooler
    } // (NumSimulationGasCooler >0)
}

void InitRefrigeration(EnergyPlusData &state)
{
    // SUBROUTINE INFORMATION:
    //       AUTHOR         Richard Raustad, FSEC
    //       DATE WRITTEN   Oct/Nov 2004
    //       MODIFIED       Hudson, ORNL July 2007, Stovall, ORNL, 2008
    //       RE-ENGINEERED  na

    // PURPOSE OF THIS SUBROUTINE:
    // Initialize (zero) global variables before simulating compressor racks and refrigerated cases
    // Several variables in this module are accumulative.  For example, unmet compressor loads are carried over
    // to the next time step. Ice loads are accumulated until melted by a defrost.  Because this module can be
    // called multiple times during any single time step, these summations need to be saved ONLY on the last time
    // through any given time step.

    // It is necessary to decrease the condenser load by the amount of heat used elsewhere
    //   via desuperheating water heaters and heating coils.
    //   Because the refrigeration system is solved before the HVAC time step loops, the
    //   refrigeration system must use the values lagged from the previous time step. In
    //   terms of energy, this should balance out and is preferable to not making the correction,
    //   in which case the condenser cooling water/air/fan energy are charged with energy
    //   loads that have been accounted elsewhere.  For consistency, the lagged value must be used,
    //   even if the Zone time step is repeated.  Therefore, the lagged variables are saved
    //   here for use during successive iterations of same zone/load time step.

    // METHODOLOGY EMPLOYED:
    // Global variables for Case Credit are located in DataHeatBalance. To Zone variables are used in the Air Heat
    // Balance in ZoneTempPredictorCorrector to calculate the zone load. To HVAC variables are used in
    // ZoneEquipmentManager to add the portion of case credits attributed to the HVAC system to the zone return air node.

    // Because we can't know apriori whether or not the time step will be repeated, we save the most recent
    // addition/subtraction to/from each accumulating variable.  If the time step is repeated,
    // this most recent addition/subtraction is reversed before the rest of the refrigeration simulation begins.

    // Used to adjust accumulative variables when time step is repeated

    auto &RefrigCase = state.dataRefrigCase->RefrigCase;
    auto &RefrigRack = state.dataRefrigCase->RefrigRack;
    auto &System = state.dataRefrigCase->System;
    auto &TransSystem = state.dataRefrigCase->TransSystem;
    auto &Condenser = state.dataRefrigCase->Condenser;
    auto &Compressor = state.dataRefrigCase->Compressor;
    auto &GasCooler = state.dataRefrigCase->GasCooler;
    auto &Secondary = state.dataRefrigCase->Secondary;
    auto &WalkIn = state.dataRefrigCase->WalkIn;
    auto &WarehouseCoil = state.dataRefrigCase->WarehouseCoil;
    auto &CoilSysCredit = state.dataRefrigCase->CoilSysCredit;
    auto &CaseWIZoneReport = state.dataRefrigCase->CaseWIZoneReport;

    // Zero display case, air-coil, and walk-in cooler credits (summed by zone)
    // to 0 each zone or sys time step
    // These 'casecredit' variables are also used to transfer energy from zone-located
    // compressor-rack condenser heat rejection, heat absorption by distribution piping,
    // suction piping, and receiver shells to zone
    if (state.dataGlobal->NumOfZones > 0) {
        if (state.dataRefrigCase->UseSysTimeStep) {
            for (int i = CoilSysCredit.l(), e = CoilSysCredit.u(); i <= e; ++i) {
                CoilSysCredit(i).reset();
            }
        } // UseSysTimeStep = true

        // Can arrive here when load call to refrigeration looks for cases/walkin systems and usetimestep is false
        if ((!state.dataRefrigCase->UseSysTimeStep) &&
            ((state.dataRefrigCase->NumSimulationCases > 0) || (state.dataRefrigCase->NumSimulationWalkIns > 0))) {

            for (auto &credit : state.dataHeatBal->RefrigCaseCredit) {
                credit.reset();
            }
            for (auto &zoneReport : CaseWIZoneReport) {
                zoneReport.reset();
            }
        }
    }

    if (state.dataRefrigCase->NumSimulationCases > 0) {
        // RefrigCase ALLOCATED to NumSimulationCases
        for (auto &refrig : RefrigCase) {
            refrig.reset_init();
        }
    } // NumSimulationCases

    if (state.dataRefrigCase->NumSimulationWalkIns > 0) {
        // WalkIn ALLOCATED to NumSimulationWalkIns
        for (int i = WalkIn.l(), e = WalkIn.u(); i <= e; ++i) {
            WalkIn(i).reset_init();
        }
    }

    if (state.dataRefrigCase->HaveChillers) {
        // HaveChillers is TRUE when NumSimulationRefrigAirChillers > 0
        // WarehouseCoil ALLOCATED to NumSimulationRefrigAirChillers
        for (int i = WarehouseCoil.l(), e = WarehouseCoil.u(); i <= e; ++i) {
            WarehouseCoil(i).reset_init();
        }
    }

    if (state.dataRefrigCase->HaveRefrigRacks) {
        // HaveRefrigRacks TRUE when NumRefrigeratedRacks > 0
        // RefrigRack ALLOCATED to NumRefrigeratedRacks
        for (int i = RefrigRack.l(), e = RefrigRack.u(); i <= e; ++i) {
            RefrigRack(i).reset_init();
        }
        for (auto &e : state.dataHeatBal->HeatReclaimRefrigeratedRack) {
            e.AvailCapacity = 0.0;
        }
        // Note don't reset basin heat to zero when no load because heater would remain on
        // RefrigRack.BasinHeaterPower = 0.0;
        // RefrigRack.BasinHeaterConsumption = 0.0;
    }

    if (state.dataRefrigCase->NumRefrigCondensers > 0) {
        // Condenser ALLOCATED to DataHeatBalance::NumRefrigCondensers
        for (int i = Condenser.l(), e = Condenser.u(); i <= e; ++i) {
            Condenser(i).reset_init();
        }
        // N don't reset basin heat to zero when no load because heater would remain on
        for (auto &e : state.dataHeatBal->HeatReclaimRefrigCondenser) {
            e.AvailCapacity = 0.0;
            e.AvailTemperature = 0.0;
        }
    }

    if (state.dataRefrigCase->NumSimulationGasCooler > 0) {
        // GasCooler ALLOCATED to NumSimulationGasCooler
        for (int i = GasCooler.l(), e = GasCooler.u(); i <= e; ++i) {
            GasCooler(i).reset_init();
        }
    }

    if (state.dataRefrigCase->NumSimulationCompressors > 0) {
        // Compressor ALLOCATED to NumSimulationCompressors
        for (int i = Compressor.l(), e = Compressor.u(); i <= e; ++i) {
            Compressor(i).reset_init();
        }
    }

    if (state.dataRefrigCase->HaveDetailedRefrig) {
        // HaveDetailedRefrig is TRUE when NumRefrigSystems > 0
        // System is ALLOCATED to NumRefrigSystems
        for (int i = System.l(), e = System.u(); i <= e; ++i) {
            System(i).reset_init();
        }
    }

    if (state.dataRefrigCase->HaveDetailedTransRefrig) {
        // HaveDetailedTransRefrig is TRUE when NumTransRefrigSystems > 0
        // TransSystem is ALLOCATED to NumTransRefrigSystems
        for (int i = TransSystem.l(), e = TransSystem.u(); i <= e; ++i) {
            TransSystem(i).reset_init();
        }
    }

    if (state.dataRefrigCase->NumSimulationSecondarySystems > 0) {
        // Secondary is ALLOCATED to NumSimulationSecondarySystems
        for (int i = Secondary.l(), e = Secondary.u(); i <= e; ++i) {
            Secondary(i).reset_init();
        }
    }

    // Accumulative and carry-over variables are not zeroed at start of each time step, only at beginning of environment
    if (state.dataGlobal->BeginEnvrnFlag && state.dataRefrigCase->InitRefrigerationMyBeginEnvrnFlag) {
        if (state.dataRefrigCase->NumSimulationCases > 0) {
            for (int i = RefrigCase.l(), e = RefrigCase.u(); i <= e; ++i) {
                RefrigCase(i).reset_init_accum();
            }
        }
        if (state.dataRefrigCase->NumRefrigSystems > 0) {
            for (auto &e : System) {
                e.UnmetEnergy = 0.0;
            }
        }
        if (state.dataRefrigCase->NumSimulationWalkIns > 0) {
            for (auto &e : WalkIn) {
                e.KgFrost = 0.0;
                e.StoredEnergy = 0.0;
            }
            for (int walkInID = 1; walkInID <= state.dataRefrigCase->NumSimulationWalkIns; ++walkInID) {
                WalkIn(walkInID).IceTemp = WalkIn(walkInID).TEvapDesign;
            }
        }
        if (state.dataRefrigCase->NumSimulationRefrigAirChillers > 0) {
            for (auto &e : WarehouseCoil) {
                e.KgFrost = 0.0;
                e.KgFrostSaved = 0.0;
            }
            for (int coilID = 1; coilID <= state.dataRefrigCase->NumSimulationRefrigAirChillers; ++coilID) {
                WarehouseCoil(coilID).IceTemp = WarehouseCoil(coilID).TEvapDesign;
                WarehouseCoil(coilID).IceTempSaved = WarehouseCoil(coilID).TEvapDesign;
            }
        }
        if (state.dataRefrigCase->NumSimulationSecondarySystems > 0) {
            for (auto &e : Secondary) {
                e.UnmetEnergy = 0.0;
            }
        }
        if (state.dataRefrigCase->NumRefrigeratedRacks > 0) {
            for (auto &e : state.dataHeatBal->HeatReclaimRefrigeratedRack) {
                e.HVACDesuperheaterReclaimedHeatTotal = 0.0;
                e.WaterHeatingDesuperheaterReclaimedHeatTotal = 0.0;
            }
            for (auto &e : RefrigRack) {
                e.LaggedUsedWaterHeater = 0.0;
                e.LaggedUsedHVACCoil = 0.0;
            }
        }
        if (state.dataRefrigCase->NumRefrigCondensers > 0) {
            for (auto &e : state.dataHeatBal->HeatReclaimRefrigCondenser) {
                e.HVACDesuperheaterReclaimedHeatTotal = 0.0;
                e.WaterHeatingDesuperheaterReclaimedHeatTotal = 0.0;
            }
            for (auto &e : Condenser) {
                e.LaggedUsedWaterHeater = 0.0;
                e.LaggedUsedHVACCoil = 0.0;
            }
        }
        for (int systemId = 1; systemId <= state.dataRefrigCase->NumRefrigSystems; ++systemId) {
            if (allocated(System(systemId).MechSCLoad)) {
                System(systemId).MechSCLoad = 0.0;
            }
            System(systemId).LSHXTrans = 0.0;
            System(systemId).LSHXTransEnergy = 0.0;
        }

        if (state.dataGlobal->TimeStepsInHour > 0.0) {
            state.dataRefrigCase->TimeStepFraction = 1.0 / double(state.dataGlobal->TimeStepsInHour);
        }
        state.dataRefrigCase->InitRefrigerationMyBeginEnvrnFlag = false;

    } // ( DataGlobals::BeginEnvrnFlag && MyBeginEnvrnFlag )

    if (!state.dataGlobal->BeginEnvrnFlag) {
        state.dataRefrigCase->InitRefrigerationMyBeginEnvrnFlag = true;
    }

    // Avoid multiplying accumulation if go through zone/load time step more than once.
    if (!state.dataGlobal->WarmupFlag) { // because no accumulation is done during warm up
        // Can arrive here when load call to refrigeration looks for cases/walkin systems and usetimestep is .FALSE.
        if ((!state.dataRefrigCase->UseSysTimeStep) &&
            ((state.dataRefrigCase->NumSimulationCases > 0) || (state.dataRefrigCase->NumSimulationWalkIns > 0))) {
            // Used to determine whether the zone time step is a repetition
            Real64 MyCurrentTime = (state.dataGlobal->HourOfDay - 1) + state.dataGlobal->TimeStep * state.dataRefrigCase->TimeStepFraction;
            if (std::abs(MyCurrentTime - state.dataRefrigCase->MyCurrentTimeSaved) < MySmallNumber) {
                // If the time step is repeated, need to return to correct values at start of time step
                if (state.dataRefrigCase->NumSimulationCases > 0) {
                    for (int caseID = 1; caseID <= state.dataRefrigCase->NumSimulationCases; ++caseID) {
                        RefrigCase(caseID).DefrostEnergy = RefrigCase(caseID).DefrostEnergySaved;
                        RefrigCase(caseID).StockingEnergy = RefrigCase(caseID).StockingEnergySaved;
                        RefrigCase(caseID).WarmEnvEnergy = RefrigCase(caseID).WarmEnvEnergySaved;
                        RefrigCase(caseID).KgFrost = RefrigCase(caseID).KgFrostSaved;
                        RefrigCase(caseID).StoredEnergy = RefrigCase(caseID).StoredEnergySaved;
                    } // CaseID
                } // NumSimulationCases
                if (state.dataRefrigCase->NumSimulationWalkIns > 0) {
                    for (int walkInID = 1; walkInID <= state.dataRefrigCase->NumSimulationWalkIns; ++walkInID) {
                        WalkIn(walkInID).KgFrost = WalkIn(walkInID).KgFrostSaved;
                        WalkIn(walkInID).StoredEnergy = WalkIn(walkInID).StoredEnergySaved;
                        WalkIn(walkInID).IceTemp = WalkIn(walkInID).IceTempSaved;
                    }
                }
                if (state.dataRefrigCase->NumRefrigSystems > 0) {
                    for (int systemID = 1; systemID <= state.dataRefrigCase->NumRefrigSystems; ++systemID) {
                        if (System(systemID).CoilFlag) {
                            continue;
                        }
                        System(systemID).UnmetEnergy = System(systemID).UnmetEnergySaved;
                    }
                }
                if (state.dataRefrigCase->NumTransRefrigSystems > 0) {
                    for (int systemID = 1; systemID <= state.dataRefrigCase->NumTransRefrigSystems; ++systemID) {
                        TransSystem(systemID).UnmetEnergyMT = TransSystem(systemID).UnmetEnergySavedMT;
                        TransSystem(systemID).UnmetEnergyLT = TransSystem(systemID).UnmetEnergySavedLT;
                    }
                }
                if (state.dataRefrigCase->NumSimulationSecondarySystems > 0) {
                    for (int secondID = 1; secondID <= state.dataRefrigCase->NumSimulationSecondarySystems; ++secondID) {
                        if (Secondary(secondID).CoilFlag) {
                            continue;
                        }
                        Secondary(secondID).UnmetEnergy = Secondary(secondID).UnmetEnergySaved;
                    }
                }

            } else {
                // First time through this Zone time step, so set saved values to those in place at start of this time step
                state.dataRefrigCase->MyCurrentTimeSaved = MyCurrentTime;
                if (state.dataRefrigCase->NumSimulationCases > 0) {
                    for (int caseID = 1; caseID <= state.dataRefrigCase->NumSimulationCases; ++caseID) {
                        RefrigCase(caseID).DefrostEnergySaved = RefrigCase(caseID).DefrostEnergy;
                        RefrigCase(caseID).StockingEnergySaved = RefrigCase(caseID).StockingEnergy;
                        RefrigCase(caseID).WarmEnvEnergySaved = RefrigCase(caseID).WarmEnvEnergy;
                        RefrigCase(caseID).KgFrostSaved = RefrigCase(caseID).KgFrost;
                        RefrigCase(caseID).StoredEnergySaved = RefrigCase(caseID).StoredEnergy;
                    } // caseid
                } // numsimulationcases
                if (state.dataRefrigCase->NumSimulationWalkIns > 0) {
                    for (int walkInID = 1; walkInID <= state.dataRefrigCase->NumSimulationWalkIns; ++walkInID) {
                        WalkIn(walkInID).KgFrostSaved = WalkIn(walkInID).KgFrost;
                        WalkIn(walkInID).StoredEnergySaved = WalkIn(walkInID).StoredEnergy;
                        WalkIn(walkInID).IceTempSaved = WalkIn(walkInID).IceTemp;
                    }
                }
                if (state.dataRefrigCase->NumRefrigSystems > 0) {
                    for (int systemID = 1; systemID <= state.dataRefrigCase->NumRefrigSystems; ++systemID) {
                        if (System(systemID).CoilFlag) {
                            continue;
                        }
                        System(systemID).UnmetEnergySaved = System(systemID).UnmetEnergy;
                    }
                }
                if (state.dataRefrigCase->NumTransRefrigSystems > 0) {
                    for (int systemID = 1; systemID <= state.dataRefrigCase->NumTransRefrigSystems; ++systemID) {
                        TransSystem(systemID).UnmetEnergySavedMT = TransSystem(systemID).UnmetEnergyMT;
                        TransSystem(systemID).UnmetEnergySavedLT = TransSystem(systemID).UnmetEnergyLT;
                    }
                }
                if (state.dataRefrigCase->NumSimulationSecondarySystems > 0) {
                    for (int secondID = 1; secondID <= state.dataRefrigCase->NumSimulationSecondarySystems; ++secondID) {
                        if (Secondary(secondID).CoilFlag) {
                            continue;
                        }
                        Secondary(secondID).UnmetEnergySaved = Secondary(secondID).UnmetEnergy;
                    }
                }
                // Following lagged variables set for consistency to value calculated prev time through HVAC time step loops
                if (allocated(state.dataHeatBal->HeatReclaimRefrigeratedRack)) {
                    for (int IRack = 1; IRack <= state.dataRefrigCase->NumRefrigeratedRacks; ++IRack) {
                        RefrigRack(IRack).LaggedUsedHVACCoil =
                            state.dataHeatBal->HeatReclaimRefrigeratedRack(IRack).HVACDesuperheaterReclaimedHeatTotal;
                        RefrigRack(IRack).LaggedUsedWaterHeater =
                            state.dataHeatBal->HeatReclaimRefrigeratedRack(IRack).WaterHeatingDesuperheaterReclaimedHeatTotal;
                    }
                }
                if (allocated(state.dataHeatBal->HeatReclaimRefrigCondenser)) {
                    for (int ICond = 1; ICond <= state.dataRefrigCase->NumRefrigCondensers; ++ICond) {
                        Condenser(ICond).LaggedUsedHVACCoil =
                            state.dataHeatBal->HeatReclaimRefrigCondenser(ICond).HVACDesuperheaterReclaimedHeatTotal;
                        Condenser(ICond).LaggedUsedWaterHeater =
                            state.dataHeatBal->HeatReclaimRefrigCondenser(ICond).WaterHeatingDesuperheaterReclaimedHeatTotal;
                    }
                }
            } // repeating same time step

        } else { // using UseSysTimeStep as a flag for a chiller system

            // Used to determine whether the system time step is a repetition
            Real64 MyStepStartTime = state.dataGlobal->CurrentTime - state.dataGlobal->TimeStepZone + state.dataHVACGlobal->SysTimeElapsed;
            if (std::abs(MyStepStartTime - state.dataRefrigCase->MyStepStartTimeSaved) < MySmallNumber) {
                // If the time step is repeated, need to return to correct values at start of time step
                if (state.dataRefrigCase->NumSimulationRefrigAirChillers > 0) {
                    for (int coilID = 1; coilID <= state.dataRefrigCase->NumSimulationRefrigAirChillers; ++coilID) {
                        WarehouseCoil(coilID).KgFrost = WarehouseCoil(coilID).KgFrostSaved;
                        WarehouseCoil(coilID).IceTemp = WarehouseCoil(coilID).IceTempSaved;
                    }
                }
            } else { // First time through this system time step or hvac loop,
                // so set saved values to those in place at start of this time step
                state.dataRefrigCase->MyStepStartTimeSaved = MyStepStartTime;
                if (state.dataRefrigCase->NumSimulationRefrigAirChillers > 0) {
                    for (int coilID = 1; coilID <= state.dataRefrigCase->NumSimulationRefrigAirChillers; ++coilID) {
                        WarehouseCoil(coilID).KgFrostSaved = WarehouseCoil(coilID).KgFrost;
                        WarehouseCoil(coilID).IceTempSaved = WarehouseCoil(coilID).IceTemp;
                    }
                }
                // Following lagged variables set for consistency to value calculated prev time through HVAC time step loops
                if (allocated(state.dataHeatBal->HeatReclaimRefrigeratedRack)) {
                    for (int IRack = 1; IRack <= state.dataRefrigCase->NumRefrigeratedRacks; ++IRack) {
                        RefrigRack(IRack).LaggedUsedHVACCoil =
                            state.dataHeatBal->HeatReclaimRefrigeratedRack(IRack).HVACDesuperheaterReclaimedHeatTotal;
                        RefrigRack(IRack).LaggedUsedWaterHeater =
                            state.dataHeatBal->HeatReclaimRefrigeratedRack(IRack).WaterHeatingDesuperheaterReclaimedHeatTotal;
                    }
                }
                if (allocated(state.dataHeatBal->HeatReclaimRefrigCondenser)) {
                    for (int ICond = 1; ICond <= state.dataRefrigCase->NumRefrigCondensers; ++ICond) {
                        Condenser(ICond).LaggedUsedHVACCoil =
                            state.dataHeatBal->HeatReclaimRefrigCondenser(ICond).HVACDesuperheaterReclaimedHeatTotal;
                        Condenser(ICond).LaggedUsedWaterHeater =
                            state.dataHeatBal->HeatReclaimRefrigCondenser(ICond).WaterHeatingDesuperheaterReclaimedHeatTotal;
                    }
                }
            } // if first time
        } //(.NOT. UseSysTimeStep)

    } // warm up flag

    if (state.dataGlobal->AnyEnergyManagementSystemInModel) {
        if (state.dataRefrigCase->NumRefrigSystems > 0) {
            for (int systemID = 1; systemID <= state.dataRefrigCase->NumRefrigSystems; ++systemID) {
                if (System(systemID).EMSOverrideOnTCondenseMin) {
                    System(systemID).TCondenseMin = System(systemID).EMSOverrideValueTCondenseMin;
                } else {
                    System(systemID).TCondenseMin = System(systemID).TCondenseMinInput;
                }
            }
        }
    }
}

void InitRefrigerationPlantConnections(EnergyPlusData &state)
{

    // SUBROUTINE INFORMATION:
    //       AUTHOR         B. Griffith
    //       DATE WRITTEN   Dec 2010
    //       MODIFIED       na
    //       RE-ENGINEERED  na

    // PURPOSE OF THIS SUBROUTINE:
    // do inits that should only occur when component model routines
    // are entered from plant, for water cooled Condensers and Refrigeration Racks

    static constexpr std::string_view RoutineName = "InitRefrigerationPlantConnections";

    auto &RefrigRack = state.dataRefrigCase->RefrigRack;
    auto &Condenser = state.dataRefrigCase->Condenser;

    // initialize plant topology information, if applicable
    if (state.dataRefrigCase->MyReferPlantScanFlag && allocated(state.dataPlnt->PlantLoop)) {
        for (int RefCondLoop = 1; RefCondLoop <= state.dataRefrigCase->NumRefrigCondensers; ++RefCondLoop) {
            if (Condenser(RefCondLoop).CondenserType != DataHeatBalance::RefrigCondenserType::Water) {
                continue;
            }

            bool errFlag = false;
            PlantUtilities::ScanPlantLoopsForObject(state,
                                                    Condenser(RefCondLoop).Name,
                                                    DataPlant::PlantEquipmentType::RefrigSystemWaterCondenser,
                                                    Condenser(RefCondLoop).plantLoc,
                                                    errFlag,
                                                    _,
                                                    _,
                                                    _,
                                                    _,
                                                    _);
            if (errFlag) {
                ShowFatalError(state, "InitRefrigerationPlantConnections: Program terminated due to previous condition(s).");
            }

            Real64 rho = state.dataPlnt->PlantLoop(Condenser(RefCondLoop).plantLoc.loopNum).glycol->getDensity(state, 20.0, RoutineName);

            if (Condenser(RefCondLoop).FlowType == CndsrFlowType::Constant) {
                Condenser(RefCondLoop).MassFlowRateMax = Condenser(RefCondLoop).DesVolFlowRate * rho;
            } else if (Condenser(RefCondLoop).FlowType == CndsrFlowType::Variable) {
                Condenser(RefCondLoop).MassFlowRateMax = Condenser(RefCondLoop).VolFlowRateMax * rho;
            }
        }

        for (int RefCompRackLoop = 1; RefCompRackLoop <= state.dataRefrigCase->NumRefrigeratedRacks; ++RefCompRackLoop) {
            if (RefrigRack(RefCompRackLoop).CondenserType != DataHeatBalance::RefrigCondenserType::Water) {
                continue;
            }

            bool errFlag = false;
            PlantUtilities::ScanPlantLoopsForObject(state,
                                                    RefrigRack(RefCompRackLoop).Name,
                                                    DataPlant::PlantEquipmentType::RefrigerationWaterCoolRack,
                                                    RefrigRack(RefCompRackLoop).plantLoc,
                                                    errFlag,
                                                    _,
                                                    _,
                                                    _,
                                                    _,
                                                    _);
            if (errFlag) {
                ShowFatalError(state, "InitRefrigerationPlantConnections: Program terminated due to previous condition(s).");
            }

            Real64 rho = state.dataPlnt->PlantLoop(RefrigRack(RefCompRackLoop).plantLoc.loopNum).glycol->getDensity(state, 20.0, RoutineName);

            if (RefrigRack(RefCompRackLoop).FlowType == CndsrFlowType::Constant) {
                RefrigRack(RefCompRackLoop).MassFlowRateMax = RefrigRack(RefCompRackLoop).DesVolFlowRate * rho;
            } else if (RefrigRack(RefCompRackLoop).FlowType == CndsrFlowType::Variable) {
                RefrigRack(RefCompRackLoop).MassFlowRateMax = RefrigRack(RefCompRackLoop).VolFlowRateMax * rho;
            }
        }

        state.dataRefrigCase->MyReferPlantScanFlag = false;
    } else if (state.dataRefrigCase->MyReferPlantScanFlag && !state.dataGlobal->AnyPlantInModel) {
        state.dataRefrigCase->MyReferPlantScanFlag = false;
    }

    if (state.dataGlobal->BeginEnvrnFlag && state.dataRefrigCase->InitRefrigerationPlantConnectionsMyBeginEnvrnFlag) {

        // do plant inits, if applicable
        if (!state.dataRefrigCase->MyReferPlantScanFlag) {
            for (int RefCondLoop = 1; RefCondLoop <= state.dataRefrigCase->NumRefrigCondensers; ++RefCondLoop) {
                if (Condenser(RefCondLoop).CondenserType != DataHeatBalance::RefrigCondenserType::Water) {
                    continue;
                }

                Real64 rho = state.dataPlnt->PlantLoop(Condenser(RefCondLoop).plantLoc.loopNum).glycol->getDensity(state, 20.0, RoutineName);

                if (Condenser(RefCondLoop).FlowType == CndsrFlowType::Constant) {
                    Condenser(RefCondLoop).MassFlowRateMax = Condenser(RefCondLoop).DesVolFlowRate * rho;
                } else if (Condenser(RefCondLoop).FlowType == CndsrFlowType::Variable) {
                    Condenser(RefCondLoop).MassFlowRateMax = Condenser(RefCondLoop).VolFlowRateMax * rho;
                }

                PlantUtilities::InitComponentNodes(
                    state, 0.0, Condenser(RefCondLoop).MassFlowRateMax, Condenser(RefCondLoop).InletNode, Condenser(RefCondLoop).OutletNode);
            }
            for (int RefCompRackLoop = 1; RefCompRackLoop <= state.dataRefrigCase->NumRefrigeratedRacks; ++RefCompRackLoop) {
                if (RefrigRack(RefCompRackLoop).CondenserType != DataHeatBalance::RefrigCondenserType::Water) {
                    continue;
                }

                Real64 rho = state.dataPlnt->PlantLoop(RefrigRack(RefCompRackLoop).plantLoc.loopNum).glycol->getDensity(state, 20.0, RoutineName);

                if (RefrigRack(RefCompRackLoop).FlowType == CndsrFlowType::Constant) {
                    RefrigRack(RefCompRackLoop).MassFlowRateMax = RefrigRack(RefCompRackLoop).DesVolFlowRate * rho;
                } else if (RefrigRack(RefCompRackLoop).FlowType == CndsrFlowType::Variable) {
                    RefrigRack(RefCompRackLoop).MassFlowRateMax = RefrigRack(RefCompRackLoop).VolFlowRateMax * rho;
                }

                PlantUtilities::InitComponentNodes(state,
                                                   0.0,
                                                   RefrigRack(RefCompRackLoop).MassFlowRateMax,
                                                   RefrigRack(RefCompRackLoop).InletNode,
                                                   RefrigRack(RefCompRackLoop).OutletNode);
            }
        }
        state.dataRefrigCase->InitRefrigerationPlantConnectionsMyBeginEnvrnFlag = false;

    } //(DataGlobals::BeginEnvrnFlag .AND. MyBeginEnvrnFlag)

    if (!state.dataGlobal->BeginEnvrnFlag) {
        state.dataRefrigCase->InitRefrigerationPlantConnectionsMyBeginEnvrnFlag = true;
    }
}

void RefrigRackData::CalcRackSystem(EnergyPlusData &state)
{

    // SUBROUTINE INFORMATION:
    //       AUTHOR         Richard Raustad, FSEC
    //       DATE WRITTEN   Oct/Nov 2004
    //       MODIFIED       Shirey, FSEC Dec 2004; Hudson, ORNL Feb 2007, July 2007
    //       RE-ENGINEERED  na

    // PURPOSE OF THIS SUBROUTINE:
    // Calculate compressor rack load, power, energy consumption, and condenser fan/pump power and consumption

    // METHODOLOGY EMPLOYED:
    // Loop through cases attached to each rack and determine total load on compressor rack

    // REFERENCES:
    // "Impact of ASHRAE Standard 62-1989 on Florida Supermarkets",
    //  Florida Solar Energy Center, FSEC-CR-910-96, Final Report, Oct. 1996

    Real64 COPFTempOutput;          // Curve value for COPFTemp curve object
    Real64 CondenserFrac;           // Fraction of condenser power as a function of outdoor temperature
    Real64 TotalHeatRejectedToZone; // Total compressor and condenser fan heat rejected to zone (based on CaseRAFactor)
    int HeatRejectZoneNum;          // Index to zone where heat is rejected
    int HeatRejectZoneNodeNum;      // Index to zone where heat is rejected
    Real64 OutWbTemp;               // Outdoor wet bulb temp at condenser air inlet node [C]
    Real64 OutDbTemp;               // Outdoor dry bulb temp at condenser air inlet node [C]
    Real64 EffectTemp;              // Effective outdoor temp when using evap condenser cooling [C]
    Real64 HumRatIn;                // Humidity ratio of inlet air to condenser [kg/kg]
    Real64 HumRatOut;               // Humidity ratio of outlet air from condenser (assumed saturated) [kg/kg]
    Real64 BPress;                  // Barometric pressure at condenser air inlet node [Pa]
    bool EvapAvail;                 // Control for evap condenser availability

    auto &RefrigCase = state.dataRefrigCase->RefrigCase;
    auto &WalkIn = state.dataRefrigCase->WalkIn;
    auto &WarehouseCoil = state.dataRefrigCase->WarehouseCoil;
    auto &AirChillerSet = state.dataRefrigCase->AirChillerSet;

    state.dataRefrigCase->TotalRackDeliveredCapacity = 0.0;
    state.dataRefrigCase->CompressorCOPactual = 0.0;
    state.dataRefrigCase->TotalCompressorPower = 0.0;
    state.dataRefrigCase->TotalCondenserFanPower = 0.0;
    state.dataRefrigCase->TotalCondenserPumpPower = 0.0;
    state.dataRefrigCase->TotalBasinHeatPower = 0.0;
    state.dataRefrigCase->TotalCondenserHeat = 0.0;
    TotalHeatRejectedToZone = 0.0;
    state.dataRefrigCase->TotalEvapWaterUseRate = 0.0;
    state.dataRefrigCase->RackSenCreditToZone = 0.0;
    state.dataRefrigCase->RackSenCreditToHVAC = 0.0;
    CondenserFrac = 0.0;
    EvapAvail = true;
    HeatRejectZoneNum = 0;
    HeatRejectZoneNodeNum = 0;

    // Loads for chiller sets are set in call to zone equipment element "SimAirChillerSet"
    // (all chiller coils within a set are located in the same zone)
    // (note non-zone, such as refrigeration, and zone equip, such as airchillersets, called at diff times)
    // Loads are then defined for each chiller coil within the set in "CalculateAirChillerSet"
    // In that subroutine, dispatch coils within each set in order specified for each zone
    //  Below will assign loads to refrigeration system or secondary loop
    // Note that this routine will go through all refrigeration systems, but loads for multiple systems
    // with interactions will not be known for the initial calls with first HVAC time step. They will,
    // however, be repeated when the last chiller set is called from ZoneEquipmentManager
    // that's why important where init goes, don't want to zero out data should keep
    if (state.dataRefrigCase->UseSysTimeStep) {
        for (int CoilSetIndex = 1; CoilSetIndex <= state.dataRefrigCase->NumRefrigChillerSets; ++CoilSetIndex) {
            AirChillerSet(CoilSetIndex).CalculateAirChillerSets(state);
        }
    }

    if (this->NumCoils > 0) {
        for (int CoilIndex = 1; CoilIndex <= this->NumCoils; ++CoilIndex) {
            int CoilID = this->CoilNum(CoilIndex);
            // already CALLed CalculateCoil(CoilID) in CoilSet specified order
            // increment TotalCoolingLoad for Compressors/condenser on each system
            state.dataRefrigCase->TotalRackDeliveredCapacity += WarehouseCoil(CoilID).TotalCoolingLoad;
            //      System(SysNum)%TotalCondDefrostCredit=System(SysNum)%TotalCondDefrostCredit + WarehouseCoil(CoilID)%HotDefrostCondCredit
        } // NumCoils systems
    } // System(SysNum)%NumCoils > 0

    if (this->NumCases > 0) {
        for (int caseNum = 1; caseNum <= this->NumCases; ++caseNum) {
            int CaseID = this->CaseNum(caseNum);
            RefrigCase(CaseID).CalculateCase(state);

            //   add evaporator load for all cases connected to rack
            state.dataRefrigCase->TotalRackDeliveredCapacity += RefrigCase(CaseID).TotalCoolingLoad;

            //   sensible and latent case credits already calculated in "CalculateCase"
            //   Now need to calculate amount of condenser heat rejection that should be applied to zone
            //                                     (used when HeatRejectionLocation = LocationZone)
            //   if walk-ins are served by rack, user must specify heat rejection zone and 100% of heat
            //   rejection goes to that zone - that is, no heat rejection goes to the HVAC return air
            if (this->HeatRejectionLocation == HeatRejLocation::Zone) {
                if (this->NumWalkIns == 0) {
                    TotalHeatRejectedToZone += RefrigCase(CaseID).TotalCoolingLoad * (1.0 - state.dataRefrigCase->CaseRAFactor);
                    //  CaseRAFactor is a module variable calculated in CalculateCase
                    //   find zone number of first case on rack (all cases are in the same zone
                    //  if HeatRejectionLocation = LocationZone and no walk-ins)
                    HeatRejectZoneNum = RefrigCase(this->CaseNum(1)).ActualZoneNum;
                    HeatRejectZoneNodeNum = RefrigCase(this->CaseNum(1)).ZoneNodeNum;
                } else { // have walk ins so no reduction in condenser heat rejection for caseRA factor
                    TotalHeatRejectedToZone += RefrigCase(CaseID).TotalCoolingLoad;
                } // no walk ins
            }
        } // NumCases
    } // Numcases on rack > 0

    if (this->NumWalkIns > 0) {
        for (int WalkInIndex = 1; WalkInIndex <= this->NumWalkIns; ++WalkInIndex) {
            int WalkInID = this->WalkInNum(WalkInIndex);
            WalkIn(WalkInID).CalculateWalkIn(state);
            state.dataRefrigCase->TotalRackDeliveredCapacity += WalkIn(WalkInID).TotalCoolingLoad;
            if (this->HeatRejectionLocation == HeatRejLocation::Zone) {
                TotalHeatRejectedToZone += WalkIn(WalkInID).TotalCoolingLoad;
                HeatRejectZoneNum = this->HeatRejectionZoneNum;
                HeatRejectZoneNodeNum = this->HeatRejectionZoneNodeNum;
            } // reject heat to zone
        } // WalkInIndex
    } // NumWalkIns>0

    if (this->HeatRejectionLocation == HeatRejLocation::Zone) {
        COPFTempOutput = Curve::CurveValue(state, this->COPFTempPtr, state.dataLoopNodes->Node(HeatRejectZoneNodeNum).Temp);
        EvapAvail = false;
    } else {
        if (this->OutsideAirNodeNum != 0) {
            OutDbTemp = state.dataLoopNodes->Node(this->OutsideAirNodeNum).Temp;
            BPress = state.dataLoopNodes->Node(this->OutsideAirNodeNum).Press;
        } else {
            OutDbTemp = state.dataEnvrn->OutDryBulbTemp;
            BPress = state.dataEnvrn->OutBaroPress;
        }
        EffectTemp = OutDbTemp;

        // IF schedule exists, evap condenser can be scheduled OFF
        // Check schedule to determine evap condenser availability
        if (this->evapAvailSched != nullptr && this->evapAvailSched->getCurrentVal() == 0) {
            EvapAvail = false;
        }

        // Evaporative condensers will have their water flow shut off in cold months to avoid
        //  'spectacular' icing problems.  Ideally, the user will use the evaporative schedule input
        //  to set such a schedule.  However, sometimes, users will use a single input deck to model
        //  one building in multiple climates, and may not think to put in such a schedule in the colder
        //  climates.  To accommodate such applications, the variable EvapCutOutTdb is used as an extra
        //  check.
        if (OutDbTemp < EvapCutOutTdb) {
            EvapAvail = false;
        }

        if (this->CondenserType == DataHeatBalance::RefrigCondenserType::Evap && EvapAvail) {
            // determine temps for evap cooling
            if (this->OutsideAirNodeNum != 0) {
                HumRatIn = state.dataLoopNodes->Node(this->OutsideAirNodeNum).HumRat;
            } else {
                HumRatIn = state.dataEnvrn->OutHumRat;
            } // outsideairnode
            OutWbTemp = Psychrometrics::PsyTwbFnTdbWPb(state, OutDbTemp, HumRatIn, BPress);
            EffectTemp = OutWbTemp + (1.0 - this->EvapEffect) * (OutDbTemp - OutWbTemp);
        } // evapAvail

        // Obtain water-cooled condenser inlet/outlet temps
        if (this->CondenserType == DataHeatBalance::RefrigCondenserType::Water) {
            this->InletTemp = state.dataLoopNodes->Node(this->InletNode).Temp;
            EffectTemp = state.dataLoopNodes->Node(this->InletNode).Temp + 5.0; // includes approach temp
            if (this->InletTemp < this->InletTempMin) {
                if (this->LowTempWarnIndex == 0) {
                    ShowWarningMessage(state, format("Refrigeration:CompressorRack: {}", this->Name));
                    ShowContinueError(state,
                                      "Water-cooled condenser inlet temp lower than minimum allowed temp. Check returning water temperature "
                                      "and/or minimum temperature setpoints.");
                } // LowTempWarnIndex
                ShowRecurringWarningErrorAtEnd(state,
                                               "Refrigeration Compressor Rack " + this->Name +
                                                   " - Condenser inlet temp lower than minimum allowed ... continues",
                                               this->LowTempWarnIndex);
                // END IF  !LowTempWarn
            } // InletTempMin
        } // DataHeatBalance::RefrigCondenserType::Water

        COPFTempOutput = Curve::CurveValue(state, this->COPFTempPtr, EffectTemp);
    } // Location Zone

    state.dataRefrigCase->CompressorCOPactual = this->RatedCOP * COPFTempOutput;

    if (state.dataRefrigCase->CompressorCOPactual > 0.0) {
        state.dataRefrigCase->TotalCompressorPower = state.dataRefrigCase->TotalRackDeliveredCapacity / state.dataRefrigCase->CompressorCOPactual;
        state.dataRefrigCase->TotalCondenserHeat = state.dataRefrigCase->TotalCompressorPower + state.dataRefrigCase->TotalRackDeliveredCapacity;
    } else {
        if (this->ShowCOPWarning) {
            ShowWarningError(state, format("Refrigeration:CompressorRack: {}", this->Name));
            ShowContinueError(state, " The calculated COP has a value of zero or is negative. Refer to Engineering Documentation for");
            ShowContinueError(state, " further explanation of Compressor Rack COP as a Function of Temperature Curve.");
            this->ShowCOPWarning = false;
        }
    }

    // calculate condenser fan usage here if not water-cooled; if water-cooled, fan is in separate tower object
    // fan loads > 0 only if the connected cases are operating
    if (state.dataRefrigCase->TotalRackDeliveredCapacity > 0.0 && this->CondenserType != DataHeatBalance::RefrigCondenserType::Water) {
        if (this->TotCondFTempPtr != 0) {
            if (this->HeatRejectionLocation == HeatRejLocation::Zone) {
                CondenserFrac =
                    max(0.0, min(1.0, Curve::CurveValue(state, this->TotCondFTempPtr, state.dataLoopNodes->Node(HeatRejectZoneNodeNum).Temp)));
                state.dataRefrigCase->TotalCondenserFanPower = this->CondenserFanPower * CondenserFrac;
                state.dataHeatBal->RefrigCaseCredit(HeatRejectZoneNum).SenCaseCreditToZone += this->CondenserFanPower * CondenserFrac;
            } else {
                CondenserFrac = max(0.0, min(1.0, Curve::CurveValue(state, this->TotCondFTempPtr, EffectTemp)));
                state.dataRefrigCase->TotalCondenserFanPower = this->CondenserFanPower * CondenserFrac;
            } // location zone
        } else {
            CondenserFrac = 1.0;
            state.dataRefrigCase->TotalCondenserFanPower = this->CondenserFanPower * CondenserFrac;
        } // TotCondFTempPtr
    } // Cooling Water type

    // calculate evap water use and water pump power, if applicable
    // assumes pump runs whenever evap cooling is available to minimize scaling
    if (this->CondenserType == DataHeatBalance::RefrigCondenserType::Evap && EvapAvail) {
        state.dataRefrigCase->TotalCondenserPumpPower = this->EvapPumpPower;
        HumRatOut = Psychrometrics::PsyWFnTdbTwbPb(state, EffectTemp, OutWbTemp, BPress);
        state.dataRefrigCase->TotalEvapWaterUseRate = this->CondenserAirFlowRate * CondenserFrac *
                                                      Psychrometrics::PsyRhoAirFnPbTdbW(state, BPress, OutDbTemp, HumRatIn) * (HumRatOut - HumRatIn) /
                                                      Psychrometrics::RhoH2O(EffectTemp);
    } // evapAvail
    // calculate basin water heater load
    if (this->CondenserType == DataHeatBalance::RefrigCondenserType::Evap) {
        if ((state.dataRefrigCase->TotalRackDeliveredCapacity == 0.0) && (EvapAvail) && (OutDbTemp < this->BasinHeaterSetPointTemp)) {
            state.dataRefrigCase->TotalBasinHeatPower = max(0.0, this->BasinHeaterPowerFTempDiff * (this->BasinHeaterSetPointTemp - OutDbTemp));
            // provide warning if no heater power exists
            if (state.dataRefrigCase->TotalBasinHeatPower == 0.0) {
                if (this->EvapFreezeWarnIndex == 0) {
                    ShowWarningMessage(
                        state,
                        format("Refrigeration Compressor Rack {} - Evap cooling of condenser underway with no basin heater power", this->Name));
                    ShowContinueError(state, "and condenser inlet air dry-bulb temp at or below the basin heater setpoint temperature.");
                    ShowContinueErrorTimeStamp(state, "Continuing simulation.");
                } // EvapFreezeWarnIndex == 0
                ShowRecurringWarningErrorAtEnd(state,
                                               "Refrigeration Compressor Rack " + this->Name +
                                                   " - Evap cooling of condenser underway with no basin heater power ... continues",
                                               this->EvapFreezeWarnIndex);
                // END IF
            } // TotalBasinHeatPower == 0 when at outdoor freezing conditions
        } // cap
    } // evap condenser type

    // add in compressor and condenser fan power to rack heat rejection variables if the heat rejection location is to the zone
    //   if walk-ins are served by rack, user must specify heat rejection zone and 100% of heat
    //   rejection goes to that zone - that is, no condenser heat rejection goes to the HVAC return air
    if (this->HeatRejectionLocation == HeatRejLocation::Zone) {
        state.dataRefrigCase->TotalCondenserHeat = state.dataRefrigCase->TotalRackDeliveredCapacity + state.dataRefrigCase->TotalCompressorPower +
                                                   state.dataRefrigCase->TotalCondenserFanPower;
        if (HeatRejectZoneNum > 0 && state.dataRefrigCase->TotalRackDeliveredCapacity > 0.0) {
            if (this->NumWalkIns == 0) {
                //       rack report variables for condenser heat to Zone and/or HVAC
                //       The difference between TotalHeatRejectedToZone and TotalRackDeliveredCapacity is the heat sent to return air
                state.dataRefrigCase->RackSenCreditToZone =
                    state.dataRefrigCase->TotalCondenserHeat * (TotalHeatRejectedToZone / state.dataRefrigCase->TotalRackDeliveredCapacity);
                state.dataRefrigCase->RackSenCreditToHVAC = state.dataRefrigCase->TotalCondenserHeat - state.dataRefrigCase->RackSenCreditToZone;
            } else { // walkins present and no rack heat rejection goes to return air
                state.dataRefrigCase->RackSenCreditToZone = state.dataRefrigCase->TotalCondenserHeat;
                state.dataRefrigCase->RackSenCreditToHVAC = 0.0;
            } // walkins present
            //     Update globals for use in Air Heat Balance and Zone Equipment Manager
            state.dataHeatBal->RefrigCaseCredit(HeatRejectZoneNum).SenCaseCreditToZone += state.dataRefrigCase->RackSenCreditToZone;

            state.dataHeatBal->RefrigCaseCredit(HeatRejectZoneNum).SenCaseCreditToHVAC += state.dataRefrigCase->RackSenCreditToHVAC;
        } // zone # > 0 and tot del cap > 0
    } // rack heat rejection to zone
}

void RefrigRackData::ReportRackSystem(EnergyPlusData &state, int const RackNum)
{

    // SUBROUTINE INFORMATION:
    //       AUTHOR         Richard Raustad, FSEC
    //       DATE WRITTEN   Oct/Nov 2004
    //       MODIFIED       Hudson, ORNL Feb 2007, July 2007
    //       RE-ENGINEERED  na

    // PURPOSE OF THIS SUBROUTINE:
    // To report compressor rack variables

    Real64 localTimeStep = (state.dataRefrigCase->UseSysTimeStep) ? state.dataHVACGlobal->TimeStepSys : state.dataGlobal->TimeStepZone;
    Real64 localTimeStepSec = localTimeStep * Constant::rSecsInHour;

    this->RackCompressorPower = state.dataRefrigCase->TotalCompressorPower;
    this->RackElecConsumption = state.dataRefrigCase->TotalCompressorPower * localTimeStepSec;
    this->ActualCondenserFanPower = state.dataRefrigCase->TotalCondenserFanPower;
    this->CondenserFanConsumption = state.dataRefrigCase->TotalCondenserFanPower * localTimeStepSec;
    this->RackCapacity = state.dataRefrigCase->TotalRackDeliveredCapacity;
    this->RackCoolingEnergy = state.dataRefrigCase->TotalRackDeliveredCapacity * localTimeStepSec;
    this->RackCompressorCOP = state.dataRefrigCase->CompressorCOPactual;
    this->SensHVACCreditHeatRate = state.dataRefrigCase->RackSenCreditToHVAC;
    this->SensHVACCreditHeat = state.dataRefrigCase->RackSenCreditToHVAC * localTimeStepSec;
    this->SensZoneCreditHeatRate = state.dataRefrigCase->RackSenCreditToZone;
    this->SensZoneCreditHeat = state.dataRefrigCase->RackSenCreditToZone * localTimeStepSec;
    this->EvapWaterConsumpRate = state.dataRefrigCase->TotalEvapWaterUseRate;
    this->EvapWaterConsumption = state.dataRefrigCase->TotalEvapWaterUseRate * localTimeStepSec;
    this->ActualEvapPumpPower = state.dataRefrigCase->TotalCondenserPumpPower;
    this->EvapPumpConsumption = state.dataRefrigCase->TotalCondenserPumpPower * localTimeStepSec;
    this->BasinHeaterPower = state.dataRefrigCase->TotalBasinHeatPower;
    this->BasinHeaterConsumption = state.dataRefrigCase->TotalBasinHeatPower * localTimeStepSec;
    this->CondLoad = state.dataRefrigCase->TotalCondenserHeat;
    this->CondEnergy = state.dataRefrigCase->TotalCondenserHeat * localTimeStepSec;
    // Set total rack heat rejection used for heat reclaim. Do not allow heat reclaim on stand alone (indoor) display cases.
    if (this->HeatRejectionLocation == HeatRejLocation::Zone) {
        state.dataHeatBal->HeatReclaimRefrigeratedRack(RackNum).AvailCapacity = 0.0;
    } else {
        state.dataHeatBal->HeatReclaimRefrigeratedRack(RackNum).AvailCapacity =
            state.dataRefrigCase->TotalRackDeliveredCapacity * (1.0 + 1.0 / state.dataRefrigCase->CompressorCOPactual);
    }

    // set water system demand request (if needed)
    if (this->EvapWaterSupplyMode == WaterSupply::FromTank) {
        int DemandARRID = this->EvapWaterTankDemandARRID;
        int RackTankID = this->EvapWaterSupTankID;
        state.dataWaterData->WaterStorage(RackTankID).VdotRequestDemand(DemandARRID) = this->EvapWaterConsumpRate;
    }

    SumZoneImpacts(state);
}

void RefrigCaseData::CalculateCase(EnergyPlusData &state) // Absolute pointer to refrigerated case
{

    // SUBROUTINE INFORMATION:
    //       AUTHOR         Richard Raustad and Don Shirey, FSEC
    //       DATE WRITTEN   Oct/Nov 2004
    //       MODIFIED       Therese Stovall, ORNL, May 2008
    //       RE-ENGINEERED  na

    // PURPOSE OF THIS SUBROUTINE:
    // To model refrigerated cases.

    // METHODOLOGY EMPLOYED:
    // Case performance is based on a latent component calculated using a user input curve object. The sensible
    // component is made up of all equipment loads (fan, light, anti-sweat) and the sensible case credit
    // calculated during initialization. A master schedule is used for the refrigerated case operation and
    // additional schedules control the lights and defrost operation.
    // The fan is assumed to be off for Hot-Gas and Electric defrost.

    // Unmet loads are accumulated to be met the following time step.  This usually occurs only during the
    // defrost period, so the case calls for full capacity at the end of defrost to make up for the sensible
    // case gains during the defrost period. This feature is also used if needed for restocking loads.

    // REFERENCES:

    // "Calculation of Humidity Effects on Energy Requirements of Refrigerated Display Cases",
    //  R. H. Howell, Ph. D., P.E., ASHRAE Paper, 3687 (CH-93-16-4) (RP-596)

    // "Effects of Store Relative Humidity on Refrigerated Display Case Performance",
    //  R. H. Howell, Ph. D., P.E., ASHRAE Paper, 3686 (CH-93-16-1) (RP-596)

    // "Analysis of Supermarket Dehumidification Alternatives",
    //  Electric Power Research Institute, EPRI TR-100352, Project 2891-03 Final Report, Nov. 1992.

    // "Impact of ASHRAE Standard 62-1989 on Florida Supermarkets",
    //  Florida Solar Energy Center, FSEC-CR-910-96, Final Report, Oct. 1996

    Real64 CaseCreditFraction(0.0);      // Reduction in case credits due to e.g., reduced door openings at night
    Real64 DefrostSchedule(0.0);         // Display case defrost schedule
    Real64 DefrostDripDownSchedule(0.0); // Display case drip-down schedule (allows coil to drain after defrost)
    Real64 DefrostRatio(0.0);            // ratio of defrost energy at current zone temp/humrat to defrost
    //    capacity at design condition
    Real64 LatentRatio(0.0); // ratio of latent capacity at current zone temp/humrat to
    //    latent capacity at design condition
    Real64 LatentCap_Actual(0.0);   // Refrigerated case latent capacity at specific operating conditions
    Real64 LatentCaseCredit(0.0);   // Latent case credit delivered to zone (W)
    Real64 SensibleCap_Actual(0.0); // Refrigerated case sensible capacity at specific operating conditions
    Real64 SensibleLoadPrime(0.0);  // Sensible load due to cond, conv, rad, infil (W)
    Real64 TotalCap_Actual(0.0);    // Refrigerated case total capacity at specific operating conditions
    Real64 TotalLightingLoad(0.0);  // Total lighting energy rate (W)
    Real64 TotalFan(0.0);           // Total fan energy rate (W)
    Real64 TotalAntiSweat(0.0);     // Total anti-sweat heater energy rate (W)

    // Refrigerated display case defrost type (parameters)
    // DefNone             = 0
    // DefOffCycle         = 1
    // DefHotFluid           = 2
    // DefHotFluidOnDemand   = 3 (not available)
    // DefHotFluidTerm       = 4
    // DefElectric         = 5
    // DefElectricOnDemand = 6 (not available)
    // DefElectricTerm     = 7

    state.dataRefrigCase->CaseRAFactor = 0.0;

    // Zone relative humidity (%)
    Real64 ZoneRHPercent = Psychrometrics::PsyRhFnTdbWPb(state,
                                                         state.dataLoopNodes->Node(this->ZoneNodeNum).Temp,
                                                         state.dataLoopNodes->Node(this->ZoneNodeNum).HumRat,
                                                         state.dataEnvrn->OutBaroPress) *
                           100.0;

    // Zone dew point (C)
    Real64 ZoneDewPoint = Psychrometrics::PsyTdpFnWPb(state, state.dataLoopNodes->Node(this->ZoneNodeNum).HumRat, state.dataEnvrn->OutBaroPress);

    // Display case operating temperature
    Real64 TCase = this->Temperature;

    // GET ALL SCHEDULES (note all schedules can be fractions if on/off a portion of time step)
    // case schedule should be coincident with the zone time step otherwise the simulation proceeds

    // Current value of case operating (availability) schedule
    Real64 CaseSchedule = this->availSched->getCurrentVal();
    if (CaseSchedule <= 0) {
        return;
    }
    // get defrost schedule
    if (this->defrostType > RefCaseDefrostType::None) {
        DefrostSchedule = this->defrostSched->getCurrentVal();
        DefrostDripDownSchedule = this->defrostDripDownSched->getCurrentVal();
        // next statement In case user doesn't understand concept of drip down schedule
        DefrostDripDownSchedule = max(DefrostDripDownSchedule, DefrostSchedule);
    } else {
        DefrostSchedule = 0.0;
        DefrostDripDownSchedule = 0.0;
    }

    // get product stocking schedule and load due to product stocking, if no schedule exists load is 0
    Real64 StockingSchedule = (this->stockingSched != nullptr) ? this->stockingSched->getCurrentVal() : 0.0;

    // get lighting schedule and total load due to lighting
    Real64 LightingSchedule = this->lightingSched->getCurrentVal();

    // if case credit reduction fraction schedule exists, modify both sensible and latent case credits
    // according to schedule - used to account for variable case envelope, such as night covers.
    CaseCreditFraction = (this->caseCreditFracSched != nullptr) ? this->caseCreditFracSched->getCurrentVal() : 1.0;

    // CALCULATE AUX LOADS DUE TO LIGHTS, FAN AND STOCKING
    TotalLightingLoad = this->DesignLighting * LightingSchedule;

    // Lighting energy to case
    Real64 TotalLightToCase = TotalLightingLoad * this->LightingFractionToCase;

    // Lighting energy to zone
    Real64 TotalLightToZone = TotalLightingLoad - TotalLightToCase;
    // cycle fan according to defrost schedule
    // turn fan on for none or off-cycle defrost types
    if (this->defrostType == RefCaseDefrostType::None || this->defrostType == RefCaseDefrostType::OffCycle) {
        TotalFan = this->DesignFanPower;
    } else {
        TotalFan = this->DesignFanPower * (1.0 - DefrostDripDownSchedule);
    }
    // get  load due to product stocking
    // accumulate stocking loads for reporting to help evaluate any cumulative unmet loads problems
    // only accumulate energy during actual simulation (so same if DD's are switched)

    // Total load due to stocking case product (W)
    Real64 StockingLoad = StockingSchedule * this->Length;
    if (!state.dataGlobal->WarmupFlag) {
        Real64 DeltaStockingEnergy = (StockingLoad * state.dataGlobal->TimeStepZoneSec);
        this->StockingEnergy += DeltaStockingEnergy;
    } // warm up
    // CALCULATE ALL LOADS INFLUENCED BY ZONE TEMPERATURE AND RH
    // Anti-sweat heater capacity
    switch (this->AntiSweatControlType) {
    case ASHtrCtrlType::None: {
        TotalAntiSweat = 0.0;
    } break;
    case ASHtrCtrlType::Constant: {
        TotalAntiSweat = this->AntiSweatPower;
    } break;
    case ASHtrCtrlType::Linear: {
        TotalAntiSweat =
            this->AntiSweatPower * min(1.0, max(0.0, 1.0 - (this->RatedAmbientRH - ZoneRHPercent) / (this->RatedAmbientRH - this->HumAtZeroAS)));
        TotalAntiSweat = max(this->MinimumASPower, TotalAntiSweat);
    } break;
    case ASHtrCtrlType::DewPoint: {
        TotalAntiSweat = this->AntiSweatPower * min(1.0, max(0.0, (ZoneDewPoint - TCase) / (this->RatedAmbientDewPoint - TCase)));
        TotalAntiSweat = max(this->MinimumASPower, TotalAntiSweat);
    } break;
    case ASHtrCtrlType::HeatBalance: {
        if (this->Rcase > 0.0) {
            TotalAntiSweat = (((ZoneDewPoint - state.dataLoopNodes->Node(this->ZoneNodeNum).Temp) * this->Height / Rair) +
                              ((ZoneDewPoint - TCase) * this->Height / this->Rcase));
            TotalAntiSweat = min(this->AntiSweatPower, max(this->MinimumASPower, TotalAntiSweat));
        } else {
            TotalAntiSweat = 0.0;
        }
    } break;
    default: {
        // should never execute this CASE statement
        TotalAntiSweat = 0.0;
    } break;
    }
    TotalAntiSweat *= this->Length;

    // Anti-sweat heater energy to case
    Real64 TotalASHeaterToCase = this->ASHeaterFractionToCase * TotalAntiSweat;

    // Anti-sweat heater energy to zone
    Real64 TotalASHeaterToZone = TotalAntiSweat - TotalASHeaterToCase;

    // latent capacity correction term at off-design conditions
    switch (this->LatentEnergyCurveType) {
    case EnergyEqnForm::CaseTemperatureMethod: {
        Real64 LatCapModFrac = Curve::CurveValue(state, this->LatCapCurvePtr, TCase);
        LatentRatio = max(0.0, (1.0 - (this->RatedAmbientRH - ZoneRHPercent) * LatCapModFrac));
    } break;
    case EnergyEqnForm::RHCubic: {
        LatentRatio = max(0.0, Curve::CurveValue(state, this->LatCapCurvePtr, ZoneRHPercent));
    } break;
    case EnergyEqnForm::DPCubic: {
        LatentRatio = max(0.0, Curve::CurveValue(state, this->LatCapCurvePtr, ZoneDewPoint));
    } break;
    default:
        break;
    }

    // calculate latent case load (assumes no moisture load due to stocking)
    // assume sensible case credits continue to accumulate in case during defrost/dripdown,
    //    but latent credits/load and capacity only applied outside dripdownschedule

    // Latent load placed on case at actual zone conditions (W)
    Real64 LatentLoad = this->DesignLatentCap * LatentRatio * CaseCreditFraction * (1.0 - DefrostDripDownSchedule);
    LatentCaseCredit = -LatentLoad;
    // adjust sensible loads and case credit for actual zone temperature
    // If zone temp rises above rated ambient temperature, total load can exceed case design capacity,
    // so unmet cooling loads are accumulated to meet in the next time step. (Case credit fraction allows
    //  extra insulation, e.g. night covers, or imitating a better insulated walk-in cooler)

    // used to look at extra sensible load due to excursions in zone T
    Real64 ZoneTempFactor = (state.dataLoopNodes->Node(ZoneNodeNum).Temp - TCase) / (this->RatedAmbientTemp - TCase);
    SensibleLoadPrime = this->DesignSensCaseCredit * ZoneTempFactor * CaseCreditFraction;

    // Sensible load due to heaters, lighting (W)
    Real64 SensibleLoadAux = TotalLightToCase + TotalASHeaterToCase + TotalFan + StockingLoad;

    // Total sensible load on case, may not = capacity applied (W)
    Real64 SensibleLoadTotal = SensibleLoadPrime + SensibleLoadAux;
    // include lighting and anti-sweat power not attributed to case load to sensible case credit

    // Sensible case credit delivered to zone (W)
    Real64 SensibleCaseCredit = TotalLightToZone + TotalASHeaterToZone - SensibleLoadPrime;

    // FROST:  keep track of frost build up on evaporator coil
    // avoid accumulation during warm-up to avoid reverse dd test problem
    if (!state.dataGlobal->WarmupFlag) {
        Real64 DeltaFreezeKgFrost = LatentLoad * state.dataGlobal->TimeStepZoneSec / IcetoVaporEnthalpy;
        this->KgFrost += DeltaFreezeKgFrost;
    }

    if (TCase > TempTooHotToFrost) {
        this->KgFrost = 0.0;
    }

    Real64 DefrostLoad_Actual(0.0); // heat load on case due to defrost (W)
    Real64 DefrostCap_Actual(0.0);  // power used to defrost (W)

    // DEFROST CALCULATIONS
    if (DefrostSchedule > 0.0) {
        if (this->defrostType != RefCaseDefrostType::None && this->defrostType != RefCaseDefrostType::OffCycle) {
            DefrostCap_Actual = this->DesignDefrostCap * DefrostSchedule;
            if (this->defrostType == RefCaseDefrostType::ElectricTerm || this->defrostType == RefCaseDefrostType::HotFluidTerm) {
                // calculate correction term for temperature termination defrost control
                switch (this->DefrostEnergyCurveType) {
                case EnergyEqnForm::CaseTemperatureMethod: {
                    Real64 DefCapModFrac = Curve::CurveValue(state, this->DefCapCurvePtr, TCase);
                    DefrostRatio = max(0.0, (1.0 - (this->RatedAmbientRH - ZoneRHPercent) * DefCapModFrac));
                } break;
                case EnergyEqnForm::RHCubic: {
                    DefrostRatio = max(0.0, Curve::CurveValue(state, this->DefCapCurvePtr, ZoneRHPercent));
                } break;
                case EnergyEqnForm::DPCubic: {
                    DefrostRatio = max(0.0, Curve::CurveValue(state, this->DefCapCurvePtr, ZoneDewPoint));
                } break;
                case EnergyEqnForm::None: {
                    DefrostRatio = 1.0;
                } break;
                default:
                    break;
                }
                DefrostCap_Actual *= DefrostRatio;
            }

            // frost load at start of time step (kg of ice)
            Real64 StartFrostKg = this->KgFrost;

            // Energy form of defrost capacity (J)
            Real64 defrostEnergy = DefrostCap_Actual * state.dataGlobal->TimeStepZoneSec;

            // Frost melted by defrost during a time step (kg)
            Real64 FrostMeltedKg = min(defrostEnergy / IceMeltEnthalpy, StartFrostKg);
            this->KgFrost -= FrostMeltedKg;

            // Reduce defrost heat load on case by amount of ice melted during time step
            // However, don't reduce the defrost capacity applied

            DefrostLoad_Actual = DefrostCap_Actual - FrostMeltedKg * IceMeltEnthalpy / state.dataGlobal->TimeStepZone / Constant::rSecsInHour;

            if (!state.dataGlobal->WarmupFlag) { // avoid reverse dd test problems
                // keep running total of defrost energy above that needed to melt frost for use in evaluating
                //      problems of excessive unmet loads
                this->DeltaDefrostEnergy = max(0.0, (defrostEnergy - (FrostMeltedKg * IceMeltEnthalpy)));
                this->DefrostEnergy += this->DeltaDefrostEnergy;
            }
            // If hot brine or hot gas is used for defrost, need to reduce condenser load
            // Note this condenser credit is not applied in compressor-rack systems.
            if (this->defrostType != RefCaseDefrostType::Electric && this->defrostType != RefCaseDefrostType::ElectricOnDemand &&
                this->defrostType != RefCaseDefrostType::ElectricTerm) {
                this->HotDefrostCondCredit = DefrostCap_Actual * DefrostSchedule;
            }
        } else { // no defrost or off-cycle defrost
            DefrostCap_Actual = 0.0;
            DefrostLoad_Actual = 0.0;
            this->KgFrost = 0.0;
            // Off-Cycle defrost is assumed to melt all the ice
        } // defrost type

    } else { // DefrostSchedule = 0, so no defrost load or capacity
        DefrostLoad_Actual = 0.0;
        DefrostCap_Actual = 0.0;
    } // Defrost calculations

    //*** See if capacity meets load and manage accumulated stored energy ***********************************
    // total load on case at zone conditions (W)
    Real64 TotalLoad_Actual = SensibleLoadTotal + LatentLoad + DefrostLoad_Actual;

    // Rate needed to serve all stored energy during single time step (W)
    Real64 StoredEnergyRate = this->StoredEnergy / state.dataGlobal->TimeStepZone / Constant::rSecsInHour;
    Real64 LoadRequested = TotalLoad_Actual + StoredEnergyRate;

    // prorate available cooling capacity for portion of time off due to drip down.
    Real64 CapAvail = this->DesignRatedCap * (1.0 - DefrostDripDownSchedule);
    if (CapAvail >= LoadRequested) {
        // Have more at least as much capacity available as needed, even counting stored energy
        TotalCap_Actual = LoadRequested;
        SensibleCap_Actual = SensibleLoadTotal + StoredEnergyRate;
        LatentCap_Actual = LatentLoad;
        this->StoredEnergy = 0.0;
    } else {
        // Don't have as much capacity as needed (during dripdown or period following dripdown)
        TotalCap_Actual = CapAvail;
        LatentCap_Actual = min(LatentLoad, CapAvail); // Latent load should never be > capavail, but just in case...
        SensibleCap_Actual = TotalCap_Actual - LatentCap_Actual;
        if (!state.dataGlobal->WarmupFlag) {
            this->StoredEnergy += (TotalLoad_Actual - CapAvail) * state.dataGlobal->TimeStepZoneSec;
        }
    } // CapAvail vs Load requested

    // Reset DefrostLoad_Actual to zero for non-electric defrost types, for reporting purposes
    if (this->defrostType != RefCaseDefrostType::Electric && this->defrostType != RefCaseDefrostType::ElectricOnDemand &&
        this->defrostType != RefCaseDefrostType::ElectricTerm) {
        DefrostCap_Actual = 0.0;
    }

    Real64 caseRAFraction = min(0.8, this->RAFrac);
    state.dataRefrigCase->CaseRAFactor = (1.0 - ((0.8 - caseRAFraction) / 0.8)) * 0.5;

    // Update globals for use in ZoneTemperaturePredictorCorrector (Air Heat Balance) and
    //   Zone Equipment Manager. Sum case credits to zone and case credits to HVAC

    //** this needs a moisture variable NonAirSystemMoistureResponse (equivalent of NonAirSystemResponse) to properly
    //** allocate moisture to the zone when the HVAC system is off.

    // Amount of sensible case credit applied to zone load (W)
    Real64 CaseSenCreditToZone = SensibleCaseCredit * (1.0 - state.dataRefrigCase->CaseRAFactor);

    // Amount of latent case credit applied to zone load (W)
    Real64 CaseLatCreditToZone = LatentCaseCredit * (1.0 - state.dataRefrigCase->CaseRAFactor);

    // Amount of sensible case credit applied to HVAC RA duct (W)
    Real64 CaseSenCreditToHVAC = SensibleCaseCredit * state.dataRefrigCase->CaseRAFactor;

    // Amount of latent case credit applied to HVAC RA duct (W)
    Real64 CaseLatCreditToHVAC = LatentCaseCredit * state.dataRefrigCase->CaseRAFactor;

    state.dataHeatBal->RefrigCaseCredit(this->ActualZoneNum).SenCaseCreditToZone += CaseSenCreditToZone;
    state.dataHeatBal->RefrigCaseCredit(this->ActualZoneNum).LatCaseCreditToZone += CaseLatCreditToZone;
    state.dataHeatBal->RefrigCaseCredit(this->ActualZoneNum).SenCaseCreditToHVAC += CaseSenCreditToHVAC;
    state.dataHeatBal->RefrigCaseCredit(this->ActualZoneNum).LatCaseCreditToHVAC += CaseLatCreditToHVAC;

    // ReportRefrigeratedCase(CaseID)
    this->TotalCoolingLoad = TotalCap_Actual;
    this->TotalCoolingEnergy = TotalCap_Actual * state.dataGlobal->TimeStepZoneSec;
    this->SensCoolingEnergyRate = SensibleCap_Actual;
    this->SensCoolingEnergy = SensibleCap_Actual * state.dataGlobal->TimeStepZoneSec;
    this->LatCoolingEnergyRate = LatentCap_Actual;
    this->LatCoolingEnergy = LatentCap_Actual * state.dataGlobal->TimeStepZoneSec;

    this->SensZoneCreditRate = CaseSenCreditToZone; // both positive or negative
    // This rate can be positive or negative, split into separate output variables and always report positive value
    if (CaseSenCreditToZone <= 0.0) {
        this->SensZoneCreditCoolRate = -CaseSenCreditToZone;
        this->SensZoneCreditCool = -CaseSenCreditToZone * state.dataGlobal->TimeStepZoneSec;
        this->SensZoneCreditHeatRate = 0.0;
        this->SensZoneCreditHeat = 0.0;
    } else {
        this->SensZoneCreditHeatRate = CaseSenCreditToZone;
        this->SensZoneCreditHeat = CaseSenCreditToZone * state.dataGlobal->TimeStepZoneSec;
        this->SensZoneCreditCoolRate = 0.0;
        this->SensZoneCreditCool = 0.0;
    }

    // This rate should always be negative
    this->LatZoneCreditRate = CaseLatCreditToZone;
    this->LatZoneCredit = CaseLatCreditToZone * state.dataGlobal->TimeStepZoneSec;

    this->SensHVACCreditRate = CaseSenCreditToHVAC;
    // This rate can be positive or negative, split into separate output variables and always report positive value
    if (CaseSenCreditToHVAC <= 0.0) {
        this->SensHVACCreditCoolRate = -CaseSenCreditToHVAC;
        this->SensHVACCreditCool = -CaseSenCreditToHVAC * state.dataGlobal->TimeStepZoneSec;
        this->SensHVACCreditHeatRate = 0.0;
        this->SensHVACCreditHeat = 0.0;
    } else {
        this->SensHVACCreditHeatRate = CaseSenCreditToHVAC;
        this->SensHVACCreditHeat = CaseSenCreditToHVAC * state.dataGlobal->TimeStepZoneSec;
        this->SensHVACCreditCoolRate = 0.0;
        this->SensHVACCreditCool = 0.0;
    }

    // This rate should always be negative
    this->LatHVACCreditRate = CaseLatCreditToHVAC;
    this->LatHVACCredit = CaseLatCreditToHVAC * state.dataGlobal->TimeStepZoneSec;

    this->ElecFanPower = TotalFan;
    this->ElecFanConsumption = TotalFan * state.dataGlobal->TimeStepZoneSec;
    this->ElecAntiSweatPower = TotalAntiSweat;
    this->ElecAntiSweatConsumption = TotalAntiSweat * state.dataGlobal->TimeStepZoneSec;
    this->ElecLightingPower = TotalLightingLoad;
    this->ElecLightingConsumption = TotalLightingLoad * state.dataGlobal->TimeStepZoneSec;
    this->ElecDefrostPower = DefrostCap_Actual;
    this->ElecDefrostConsumption = DefrostCap_Actual * state.dataGlobal->TimeStepZoneSec;

    this->DefEnergyCurveValue = DefrostRatio;
    this->LatEnergyCurveValue = LatentRatio;

    //**************************************************************************************************
    // Cap Energy and Kg Frost to avoid floating overflow errors
    // 1-time warning is issued. It should be rare but could happen with unrealistic inputs.

    // Collect extra sensible load above design for possible warning if that is determining factor in
    // excessively large stored energy
    if ((ZoneTempFactor * CaseCreditFraction) > 1.0) {
        if (!state.dataGlobal->WarmupFlag) {
            Real64 DeltaWarmEnvEnergy = (SensibleLoadPrime - this->DesignSensCaseCredit) * state.dataGlobal->TimeStepZoneSec;
            this->WarmEnvEnergy += DeltaWarmEnvEnergy;
        }
    }

    if (this->DefrostEnergy > MyLargeNumber) {
        this->DefrostEnergy = MyLargeNumber;
    }
    if (this->WarmEnvEnergy > MyLargeNumber) {
        this->WarmEnvEnergy = MyLargeNumber;
    }
    if (this->StockingEnergy > MyLargeNumber) {
        this->StockingEnergy = MyLargeNumber;
    }
    if (this->StoredEnergy > MyLargeNumber) {
        this->StoredEnergy = MyLargeNumber;
        if (this->ShowStoreEnergyWarning) {
            ShowWarningError(state, format("Refrigeration:Case: {}", this->Name));
            if (this->StockingEnergy >= this->DefrostEnergy) {
                if (this->StockingEnergy >= this->WarmEnvEnergy) {
                    ShowContinueError(state, " This case has insufficient capacity to meet excess energy associated with stocking.");
                    ShowContinueError(state, " Refer to documentation for further explanation of product stocking requirements and");
                    ShowContinueError(state, " Total Cooling Capacity.");
                } else {
                    ShowContinueError(state,
                                      " This case has insufficient capacity to meet excess energy associated with a zone environment temperature "
                                      "greater than the design ambient for the case.");
                    ShowContinueError(state, " Refer to documentation for further explanation of ");
                    ShowContinueError(state, " Total Cooling Capacity.");
                } // Stocking energy > warm environment energy
            } else {
                if (this->DefrostEnergy >= this->WarmEnvEnergy) {
                    ShowContinueError(state, " This case has insufficient capacity to meet excess energy associated with defrost.");
                    ShowContinueError(state, " Refer to documentation for further explanation of defrost control requirements and");
                    ShowContinueError(state, " recommendations regarding Total Cooling Capacity, Sensible Heat Ratio, and Defrost Capacity.");
                } else {
                    ShowContinueError(state,
                                      " This case has insufficient capacity to meet excess energy associated with a zone environment temperature "
                                      "greater than the design ambient for the case.");
                    ShowContinueError(state, " Refer to documentation for further explanation of ");
                    ShowContinueError(state, " Total Cooling Capacity.");
                } // defrost energy > warm environment energy
            } // stock > defrost ELSE
            this->ShowStoreEnergyWarning = false; // only give this warning once for any one case
        } // showstoreenergy warning true
    } // stored energy > large number

    if (this->KgFrost > MyLargeNumber) {
        this->KgFrost = MyLargeNumber;
        if (this->ShowFrostWarning) {
            ShowWarningError(state, format("Refrigeration:Case: {}", this->Name));
            ShowContinueError(state, " This case has insufficient defrost capacity to remove the excess frost accumulation.");
            ShowContinueError(state, " Refer to documentation for further explanation of product stocking requirements and");
            ShowContinueError(state, " recommendations regarding Total Cooling Capacity, Sensible Heat Ratio, and Latent Heat Ratio.");
            this->ShowFrostWarning = false;
        }
    }
}

PlantComponent *RefrigCondenserData::factory(EnergyPlusData &state, std::string const &objectName)
{
    // Process the input data for boilers if it hasn't been done already
    if (state.dataRefrigCase->GetRefrigerationInputFlag) {
        CheckRefrigerationInput(state);
        state.dataRefrigCase->GetRefrigerationInputFlag = false;
    }
    // Now look for this particular object in list
    for (auto &obj : state.dataRefrigCase->Condenser) {
        if (obj.Name == objectName) {
            return &obj;
        }
    }
    // If we didn't find it, fatal
    ShowFatalError(state, format("LocalRefrigCondenserFactory: Error getting inputs for object named: {}", objectName)); // LCOV_EXCL_LINE
    // Shut up the compiler
    return nullptr; // LCOV_EXCL_LINE
}

void RefrigCondenserData::onInitLoopEquip(EnergyPlusData &state, [[maybe_unused]] const PlantLocation &calledFromLocation)
{
    InitRefrigeration(state);
    InitRefrigerationPlantConnections(state);
}

void RefrigCondenserData::simulate(EnergyPlusData &state,
                                   [[maybe_unused]] const PlantLocation &calledFromLocation,
                                   bool const FirstHVACIteration,
                                   [[maybe_unused]] Real64 &CurLoad,
                                   [[maybe_unused]] bool const RunFlag)
{

    // SUBROUTINE INFORMATION:
    //       AUTHOR         Randy Hudson, ORNL
    //       DATE WRITTEN   July 2007
    //       MODIFIED       Therese Stovall, ORNL May 2008
    //                      Brent Griffith, NREL Oct 2010, generalize fluid properties
    //                        plant upgrades, moved where called from to SimPlantEquip from ManageNonZoneEquipment
    //       RE-ENGINEERED  na

    // PURPOSE OF THIS SUBROUTINE:
    // Simulates the water-cooled refrigeration condenser object.
    // Modified to add condensers for detailed refrigeration systems and to
    // avoid double-counting heat rejection that has been used in desuperheater
    // hvac coils or water heaters.

    // METHODOLOGY EMPLOYED:
    // Called from SimPlantEquip in PlantLoopEquipment , previously was called from Non-Zone Equipment Manager
    // Flow is requested and the actual available flow is set.  The outlet temperature is calculated.

    static constexpr std::string_view RoutineName("SimRefrigCondenser");
    int PlantInletNode(0);
    int PlantOutletNode(0);
    PlantLocation PlantLoc{};

    InitRefrigerationPlantConnections(state);

    std::string TypeName;
    std::string ErrIntro;

    // set variables depending upon system type
    PlantInletNode = this->InletNode;
    PlantOutletNode = this->OutletNode;
    PlantLoc = this->plantLoc;

    state.dataRefrigCase->TotalCondenserHeat = this->CondLoad;
    TypeName = "Refrigeration:Condenser:WaterCooled";
    ErrIntro = "Condenser for refrigeration system ";

    // Current condenser is water cooled
    // Make demand request on first HVAC iteration

    // get cooling fluid properties
    Real64 rho = state.dataPlnt->PlantLoop(PlantLoc.loopNum).glycol->getDensity(state, this->InletTemp, RoutineName);
    Real64 Cp = state.dataPlnt->PlantLoop(PlantLoc.loopNum).glycol->getSpecificHeat(state, this->InletTemp, RoutineName);

    if (this->FlowType == CndsrFlowType::Variable && state.dataRefrigCase->TotalCondenserHeat > 0.0) {

        this->OutletTemp = this->outletTempSched->getCurrentVal();

        if (this->OutletTemp == this->InletTemp) {

            if (this->HighInletWarnIndex == 0) {
                ShowSevereError(
                    state,
                    format("{}, \"{}\" : has inlet water temp equal to desired outlet temp. Excessive flow resulting. ", ErrIntro, this->Name));
                ShowContinueError(state, "cooling water is not cold enough to reach desired outlet temperature");
            }
            ShowRecurringWarningErrorAtEnd(state,
                                           ErrIntro + ", \"" + this->Name + "\" : has inlet water temp equal to desired outlet temp.... continues. ",
                                           this->HighInletWarnIndex);
            this->VolFlowRate = 9999.0;
            this->MassFlowRate = this->VolFlowRate * rho;
        } else {
            Real64 DeltaT = this->OutletTemp - this->InletTemp;
            this->MassFlowRate = state.dataRefrigCase->TotalCondenserHeat / Cp / DeltaT;
            // Check for maximum flow in the component
            if (this->MassFlowRate > this->MassFlowRateMax) {
                if (this->HighFlowWarnIndex == 0) {
                    ShowWarningMessage(state, format("{}{}", TypeName, this->Name));
                    ShowContinueError(state, "Requested condenser water mass flow rate greater than maximum allowed value. ");
                    ShowContinueError(state, "Flow reset to maximum value.");
                } // HighFlowWarnIndex
                ShowRecurringWarningErrorAtEnd(
                    state, ErrIntro + this->Name + " - Flow rate higher than maximum allowed ... continues", this->HighFlowWarnIndex);
                // END IF
                this->MassFlowRate = this->MassFlowRateMax;
            }
        } // compare outlet T to inlet T

    } else if (this->FlowType == CndsrFlowType::Constant && state.dataRefrigCase->TotalCondenserHeat > 0.0) {
        // this part for constant flow condition
        this->VolFlowRate = this->DesVolFlowRate;
        this->MassFlowRate = this->VolFlowRate * rho;

    } else if (state.dataRefrigCase->TotalCondenserHeat == 0.0) {
        this->MassFlowRate = 0.0;

    } // on flow type
    // check against plant, might get changed.
    PlantUtilities::SetComponentFlowRate(state, this->MassFlowRate, PlantInletNode, PlantOutletNode, PlantLoc);

    this->VolFlowRate = this->MassFlowRate / rho;

    if (this->MassFlowRate > 0) {
        this->OutletTemp = state.dataRefrigCase->TotalCondenserHeat / (this->MassFlowRate * Cp) + state.dataLoopNodes->Node(PlantInletNode).Temp;
    } else {
        this->OutletTemp = this->InletTemp;
        if ((state.dataRefrigCase->TotalCondenserHeat > 0.0) && (!FirstHVACIteration)) {

            ShowRecurringWarningErrorAtEnd(
                state,
                TypeName + this->Name +
                    "Water-cooled condenser has no cooling water flow. Heat is not being rejected from compressor rack condenser.",
                this->NoFlowWarnIndex);
        }
    }
    // Check outlet water temp for max value
    if (this->OutletTemp > this->OutletTempMax) {
        if (this->HighTempWarnIndex == 0) {
            ShowWarningMessage(state, format("{}{}", TypeName, this->Name));
            ShowContinueError(state,
                              "Water-cooled condenser outlet temp higher than maximum allowed temp. Check flow rates and/or temperature setpoints.");
        }
        ShowRecurringWarningErrorAtEnd(
            state, ErrIntro + this->Name + " - Condenser outlet temp higher than maximum allowed ... continues", this->HighTempWarnIndex);
    }

    this->UpdateCondenserOutletNode(state);
}

PlantComponent *RefrigRackData::factory(EnergyPlusData &state, std::string const &objectName)
{
    // Process the input data for boilers if it hasn't been done already
    if (state.dataRefrigCase->GetRefrigerationInputFlag) {
        CheckRefrigerationInput(state);
        state.dataRefrigCase->GetRefrigerationInputFlag = false;
    }
    // Now look for this particular object in list
    for (auto &obj : state.dataRefrigCase->RefrigRack) {
        if (obj.Name == objectName) {
            return &obj;
        }
    }
    // If we didn't find it, fatal
    ShowFatalError(state, format("LocalRefrigRackFactory: Error getting inputs for object named: {}", objectName)); // LCOV_EXCL_LINE
    // Shut up the compiler
    return nullptr; // LCOV_EXCL_LINE
}

void RefrigRackData::onInitLoopEquip(EnergyPlusData &state, [[maybe_unused]] const PlantLocation &calledFromLocation)
{
    InitRefrigeration(state);
    InitRefrigerationPlantConnections(state);
}

void RefrigRackData::simulate(EnergyPlusData &state,
                              [[maybe_unused]] const PlantLocation &calledFromLocation,
                              bool const FirstHVACIteration,
                              [[maybe_unused]] Real64 &CurLoad,
                              [[maybe_unused]] bool const RunFlag)
{

    // SUBROUTINE INFORMATION:
    //       AUTHOR         Randy Hudson, ORNL
    //       DATE WRITTEN   July 2007
    //       MODIFIED       Therese Stovall, ORNL May 2008
    //                      Brent Griffith, NREL Oct 2010, generalize fluid properties
    //                        plant upgrades, moved where called from to SimPlantEquip from ManageNonZoneEquipment
    //       RE-ENGINEERED  na

    // PURPOSE OF THIS SUBROUTINE:
    // Simulates the water-cooled refrigeration condenser object.
    // Modified to add condensers for detailed refrigeration systems and to
    // avoid double-counting heat rejection that has been used in desuperheater
    // hvac coils or water heaters.

    // METHODOLOGY EMPLOYED:
    // Called from SimPlantEquip in PlantLoopEquipment , previously was called from Non-Zone Equipment Manager
    // Flow is requested and the actual available flow is set.  The outlet temperature is calculated.

    static constexpr std::string_view RoutineName("SimRefrigCondenser");
    int PlantInletNode(0);
    int PlantOutletNode(0);
    PlantLocation PlantLoc{};

    InitRefrigerationPlantConnections(state);

    std::string TypeName;
    std::string ErrIntro;

    // set variables depending upon system type
    PlantInletNode = this->InletNode;
    PlantOutletNode = this->OutletNode;
    PlantLoc = this->plantLoc;

    state.dataRefrigCase->TotalCondenserHeat =
        state.dataHeatBal->HeatReclaimRefrigeratedRack(this->MyIdx).AvailCapacity - this->LaggedUsedWaterHeater - this->LaggedUsedHVACCoil;
    TypeName = "Refrigeration:CompressorRack:";
    ErrIntro = "Condenser for refrigeration rack ";

    // Current condenser is water cooled
    // Make demand request on first HVAC iteration

    // get cooling fluid properties
    Real64 rho = state.dataPlnt->PlantLoop(PlantLoc.loopNum).glycol->getDensity(state, this->InletTemp, RoutineName);
    Real64 Cp = state.dataPlnt->PlantLoop(PlantLoc.loopNum).glycol->getSpecificHeat(state, this->InletTemp, RoutineName);

    if (this->FlowType == CndsrFlowType::Variable && state.dataRefrigCase->TotalCondenserHeat > 0.0) {
        this->OutletTemp = this->outletTempSched->getCurrentVal();

        if (this->OutletTemp == this->InletTemp) {

            if (this->HighInletWarnIndex == 0) {
                ShowSevereError(
                    state,
                    format("{}, \"{}\" : has inlet water temp equal to desired outlet temp. Excessive flow resulting. ", ErrIntro, this->Name));
                ShowContinueError(state, "cooling water is not cold enough to reach desired outlet temperature");
            }
            ShowRecurringWarningErrorAtEnd(state,
                                           ErrIntro + ", \"" + this->Name + "\" : has inlet water temp equal to desired outlet temp.... continues. ",
                                           this->HighInletWarnIndex);
            this->VolFlowRate = 9999.0;
            this->MassFlowRate = this->VolFlowRate * rho;
        } else {
            Real64 DeltaT = this->OutletTemp - this->InletTemp;
            this->MassFlowRate = state.dataRefrigCase->TotalCondenserHeat / Cp / DeltaT;
            // Check for maximum flow in the component
            if (this->MassFlowRate > this->MassFlowRateMax) {
                if (this->HighFlowWarnIndex == 0) {
                    ShowWarningMessage(state, format("{}{}", TypeName, this->Name));
                    ShowContinueError(state, "Requested condenser water mass flow rate greater than maximum allowed value. ");
                    ShowContinueError(state, "Flow reset to maximum value.");
                } // HighFlowWarnIndex
                ShowRecurringWarningErrorAtEnd(
                    state, ErrIntro + this->Name + " - Flow rate higher than maximum allowed ... continues", this->HighFlowWarnIndex);
                // END IF
                this->MassFlowRate = this->MassFlowRateMax;
            }
        } // compare outlet T to inlet T

    } else if (this->FlowType == CndsrFlowType::Constant && state.dataRefrigCase->TotalCondenserHeat > 0.0) {
        // this part for constant flow condition
        this->VolFlowRate = this->DesVolFlowRate;
        this->MassFlowRate = this->VolFlowRate * rho;

    } else if (state.dataRefrigCase->TotalCondenserHeat == 0.0) {
        this->MassFlowRate = 0.0;

    } // on flow type
    // check against plant, might get changed.
    PlantUtilities::SetComponentFlowRate(state, this->MassFlowRate, PlantInletNode, PlantOutletNode, PlantLoc);

    this->VolFlowRate = this->MassFlowRate / rho;

    if (this->MassFlowRate > 0) {
        this->OutletTemp = state.dataRefrigCase->TotalCondenserHeat / (this->MassFlowRate * Cp) + state.dataLoopNodes->Node(PlantInletNode).Temp;
    } else {
        this->OutletTemp = this->InletTemp;
        if ((state.dataRefrigCase->TotalCondenserHeat > 0.0) && (!FirstHVACIteration)) {

            ShowRecurringWarningErrorAtEnd(
                state,
                TypeName + this->Name +
                    "Water-cooled condenser has no cooling water flow. Heat is not being rejected from compressor rack condenser.",
                this->NoFlowWarnIndex);
        }
    }
    // Check outlet water temp for max value
    if (this->OutletTemp > this->OutletTempMax) {
        if (this->HighTempWarnIndex == 0) {
            ShowWarningMessage(state, format("{}{}", TypeName, this->Name));
            ShowContinueError(state,
                              "Water-cooled condenser outlet temp higher than maximum allowed temp. Check flow rates and/or temperature setpoints.");
        }
        ShowRecurringWarningErrorAtEnd(
            state, ErrIntro + this->Name + " - Condenser outlet temp higher than maximum allowed ... continues", HighTempWarnIndex);
    }

    this->UpdateCondenserOutletNode(state);
}

void RefrigCondenserData::UpdateCondenserOutletNode(EnergyPlusData &state) const
{

    // SUBROUTINE INFORMATION:
    //       AUTHOR         Randy Hudson, ORNL
    //       DATE WRITTEN   July 2007
    //       MODIFIED       na
    //       RE-ENGINEERED  na

    // PURPOSE OF THIS SUBROUTINE:
    // Updates the node variables with local variables.

    // Pass all variables from inlet to outlet node
    PlantUtilities::SafeCopyPlantNode(state, this->InletNode, this->OutletNode);

    // Set outlet node variables that are possibly changed
    state.dataLoopNodes->Node(this->OutletNode).Temp = this->OutletTemp;
}
void RefrigCondenserData::oneTimeInit([[maybe_unused]] EnergyPlusData &state)
{
}
void RefrigCondenserData::oneTimeInit_new([[maybe_unused]] EnergyPlusData &state)
{
}

void RefrigRackData::UpdateCondenserOutletNode(EnergyPlusData &state) const
{

    // SUBROUTINE INFORMATION:
    //       AUTHOR         Randy Hudson, ORNL
    //       DATE WRITTEN   July 2007
    //       MODIFIED       na
    //       RE-ENGINEERED  na

    // PURPOSE OF THIS SUBROUTINE:
    // Updates the node variables with local variables.

    // Pass all variables from inlet to outlet node
    PlantUtilities::SafeCopyPlantNode(state, this->InletNode, this->OutletNode);

    // Set outlet node variables that are possibly changed
    state.dataLoopNodes->Node(this->OutletNode).Temp = this->OutletTemp;
}
void RefrigRackData::oneTimeInit([[maybe_unused]] EnergyPlusData &state)
{
}

void RefrigRackData::oneTimeInit_new([[maybe_unused]] EnergyPlusData &state)
{
}

void SimulateDetailedRefrigerationSystems(EnergyPlusData &state)
{

    // SUBROUTINE INFORMATION:
    //       AUTHOR         Therese Stovall, ORNL, Assisted by Hugh Henderson
    //       DATE WRITTEN   Spring 2008
    //       Based upon ManageRefrigeratedCaseRacks by Richard Raustad, FSEC
    //          Oct/Nov 2004, and MODIFIED by Shirey, FSEC Dec 2004
    //       RE-ENGINEERED  na

    // PURPOSE OF THIS SUBROUTINE:
    // This subroutine is called to simulate detailed refrigeration systems

    // METHODOLOGY EMPLOYED:
    // Each refrigeration system is modeled by first simulating the attached refrigerated cases.  The sum
    // of the total heat transfer for all attached cases determines the load on the compressor rack.
    // Iterations are used here to account for load transfer between independent refrigeration systems
    // via mechanical subcoolers.
    // The logical variable, UseSysTimeStep, determines whether we are evaluating only systems driven by
    // ZoneEquipmentManager on the system time step, or only system driven by HVACManager on the zone time step.

    static constexpr std::string_view RoutineName = "SimulateDetailedRefrigerationSystems";
    Real64 constexpr MaxDelTFloatFrac = 0.5; // max fraction allowed for difference between case and evaporator temperature

    auto &RefrigCase = state.dataRefrigCase->RefrigCase;
    auto &System = state.dataRefrigCase->System;
    auto &Condenser = state.dataRefrigCase->Condenser;
    auto &Subcooler = state.dataRefrigCase->Subcooler;
    auto &Secondary = state.dataRefrigCase->Secondary;
    auto &WalkIn = state.dataRefrigCase->WalkIn;
    auto &WarehouseCoil = state.dataRefrigCase->WarehouseCoil;
    auto &AirChillerSet = state.dataRefrigCase->AirChillerSet;
    auto &CoilSysCredit = state.dataRefrigCase->CoilSysCredit;

    Real64 localTimeStep = (state.dataRefrigCase->UseSysTimeStep) ? state.dataHVACGlobal->TimeStepSys : state.dataGlobal->TimeStepZone;
    Real64 localTimeStepSec = localTimeStep * Constant::rSecsInHour;

    // Cascade condenser assumes a constant approach delta T (Tcond - Tevap), not f(load)

    // Loads for chiller sets are set in call to zone equipment element "SimAirChillerSet"
    // (all chiller coils within a set are located in the same zone)
    // (note non-zone, such as refrigeration, and zone equip, such as airchillersets, called at diff times)
    // Loads are then defined for each chiller coil within the set in "CalculateAirChillerSet"
    // In that subroutine, dispatch coils within each set in order specified for each zone
    //  Below will assign loads to refrigeration system or secondary loop
    // Note that this routine will go through all refrigeration systems, but loads for multiple systems
    // with interactions will not be known for the initial calls with first HVAC time step. They will,
    // however, be repeated when the last chiller set is called from ZoneEquipmentManager
    // that's why important where init goes, don't want to zero out data should keep
    if (state.dataRefrigCase->UseSysTimeStep) {
        for (int CoilSetIndex = 1; CoilSetIndex <= state.dataRefrigCase->NumRefrigChillerSets; ++CoilSetIndex) {
            AirChillerSet(CoilSetIndex).CalculateAirChillerSets(state);
        }
    }

    // Do refrigeration system loop outside of iterative solution to initialize time step and
    //  calculate case, walk-in, and secondary loop loads (that won't change during balance
    //  of refrigeration system iterations) and prepare initial estimates for the iterative system solution
    for (auto &thisSys : System) {
        // Only do those systems appropriate for this analysis, supermarket type on load time step or coil type on sys time step
        if (((!state.dataRefrigCase->UseSysTimeStep) && (!thisSys.CoilFlag)) || ((state.dataRefrigCase->UseSysTimeStep) && (thisSys.CoilFlag))) {
            if (thisSys.NumCases > 0) {
                for (int CaseIndex = 1; CaseIndex <= thisSys.NumCases; ++CaseIndex) {
                    auto &thisCase = RefrigCase(thisSys.CaseNum(CaseIndex));
                    thisCase.CalculateCase(state);
                    //  TevapDesign calc in Get Input to meet lowest evap temp of any load on the system.
                    //  Tevap needed is either fixed at this design value,
                    //  or allowed to float to meet lowest T needed among all loads served by the system
                    //  (Floating Tevap = Design Tevap unless load <= Design cap)
                    if (thisSys.CompSuctControl == CompressorSuctionPressureCtrl::ConstantSuctionTemperature) {
                        thisSys.TEvapNeeded = thisSys.TEvapDesign;
                    } else { // calculate floating T evap
                        Real64 LoadFrac = min(1.0, (thisCase.TotalCoolingLoad / thisCase.DesignRatedCap));
                        Real64 MaxTEvap = thisCase.Temperature - (thisCase.Temperature - thisCase.EvapTempDesign) * max(LoadFrac, MaxDelTFloatFrac);
                        // Compare Tevap for this case to max allowed for all previous cases on this suction group and set at the MINIMUM of the
                        // two
                        if (CaseIndex == 1) { // note use case index, not caseid here to get first case on this suction group/system
                            thisSys.TEvapNeeded = MaxTEvap;
                        } else {
                            thisSys.TEvapNeeded = min(MaxTEvap, thisSys.TEvapNeeded);
                        }
                    } // floating or constant evap temperature
                    // increment TotalCoolingLoad for Compressors/condenser on each system and defrost condenser credits for heat recovery
                    thisSys.TotalCoolingLoad += thisCase.TotalCoolingLoad;
                    thisSys.TotalCondDefrostCredit += thisCase.HotDefrostCondCredit;
                } // NumCases
            } // Num of cases > 0

            if (thisSys.NumWalkIns > 0) {
                for (int WalkInIndex = 1; WalkInIndex <= thisSys.NumWalkIns; ++WalkInIndex) {
                    auto &thisWalkIn = WalkIn(thisSys.WalkInNum(WalkInIndex));
                    thisWalkIn.CalculateWalkIn(state);
                    if (thisSys.CompSuctControl == CompressorSuctionPressureCtrl::ConstantSuctionTemperature) {
                        thisSys.TEvapNeeded = thisSys.TEvapDesign;
                    } else { // calculate floating T evap
                        Real64 LoadFrac = min(1.0, (thisWalkIn.TotalCoolingLoad / thisWalkIn.DesignRatedCap));
                        Real64 MaxTEvap =
                            thisWalkIn.Temperature - (thisWalkIn.Temperature - thisWalkIn.TEvapDesign) * max(LoadFrac, MaxDelTFloatFrac);
                        //  Compare maxTevap for this walk in to max allowed for cases and for all
                        //  previous walk ins on this suction group and set at the MINIMUM of the two
                        if (WalkInIndex == 1 && thisSys.NumCases == 0) {
                            thisSys.TEvapNeeded = MaxTEvap;
                        } else {
                            thisSys.TEvapNeeded = min(MaxTEvap, thisSys.TEvapNeeded);
                        }
                    } // floating or constant evap temperature
                    // increment TotalCoolingLoad for Compressors/condenser on each system
                    thisSys.TotalCoolingLoad += thisWalkIn.TotalCoolingLoad;
                    thisSys.TotalCondDefrostCredit += thisWalkIn.HotDefrostCondCredit;
                } // NumWalkIns systems
            } // thisSys%NumWalkIns > 0

            if (thisSys.NumCoils > 0) {
                for (int CoilIndex = 1; CoilIndex <= thisSys.NumCoils; ++CoilIndex) {
                    int CoilID = thisSys.CoilNum(CoilIndex);
                    // already CALLed CalculateCoil(CoilID) in CoilSet specified order
                    thisSys.TEvapNeeded = thisSys.TEvapDesign; // floating or constant evap temperature
                    // increment TotalCoolingLoad for Compressors/condenser on each system
                    thisSys.TotalCoolingLoad += WarehouseCoil(CoilID).TotalCoolingLoad;
                    thisSys.TotalCondDefrostCredit += WarehouseCoil(CoilID).HotDefrostCondCredit;
                } // NumCoils systems
            } // thisSys%NumCoils > 0

            if (thisSys.NumSecondarys > 0) {
                for (int SecondIndex = 1; SecondIndex <= thisSys.NumSecondarys; ++SecondIndex) {
                    int SecondID = thisSys.SecondaryNum(SecondIndex);
                    Secondary(SecondID).CalculateSecondary(state, SecondID);
                    if (thisSys.CompSuctControl == CompressorSuctionPressureCtrl::ConstantSuctionTemperature) {
                        thisSys.TEvapNeeded = thisSys.TEvapDesign;
                    } else { // check for lowest T evap design among the secondary systems and
                        //  Compare Tevap for this second to max allowed for cases, walk ins, and
                        //  for all previous secondary loops on this suction group and set
                        //  at the MINIMUM (note secondary loops control capacity with
                        //  brine flow rate, so don't float above their design evap temperature)
                        if (SecondIndex == 1 && thisSys.NumNonCascadeLoads == 0) {
                            thisSys.TEvapNeeded = Secondary(SecondID).TEvapDesign;
                        } else {
                            thisSys.TEvapNeeded = min(Secondary(SecondID).TEvapDesign, thisSys.TEvapNeeded);
                        }
                    } // floating or constant evap temperature
                    // increment TotalCoolingLoad for Compressors/condenser on each system
                    thisSys.SumSecondaryLoopLoad += Secondary(SecondID).TotalCoolingLoad;
                    thisSys.TotalCondDefrostCredit += Secondary(SecondID).HotDefrostCondCredit;
                } // NumSecondarys systems
            } // thisSys%NumSecondarys > 0

            // add suction pipe heat gains (W) if input by user
            // Suction pipe heat gains aren't included in the reported total system load, but are heat gains that must be met in
            //  condenser and compressor loads. However, secondary dist piping and receiver gains are included
            //  in the total secondary system loads.
            thisSys.PipeHeatLoad = 0.0;
            if (thisSys.SumUASuctionPiping > MySmallNumber) {
                Real64 SuctionPipeZoneTemp = state.dataLoopNodes->Node(thisSys.SuctionPipeZoneNodeNum)
                                                 .Temp; // Temperature for zone identified as environment for suction pipe heat gains, C
                thisSys.PipeHeatLoad = thisSys.SumUASuctionPiping * (SuctionPipeZoneTemp - thisSys.TEvapNeeded);
                // pipe heat load is a positive number (ie. heat absorbed by pipe, so needs to be subtracted
                //     from refrigcasecredit (- for cooling zone, + for heating zone)
                int SuctionPipeActualZoneNum = thisSys.SuctionPipeActualZoneNum;
                if (state.dataRefrigCase->UseSysTimeStep) {
                    CoilSysCredit(SuctionPipeActualZoneNum).SenCreditToZoneRate -= thisSys.PipeHeatLoad;
                    CoilSysCredit(SuctionPipeActualZoneNum).ReportSenCoolingToZoneRate = -CoilSysCredit(SuctionPipeActualZoneNum).SenCreditToZoneRate;
                }
                // Can arrive here when load call to refrigeration looks for cases/walkin systems and usetimestep is .FALSE.
                if ((!state.dataRefrigCase->UseSysTimeStep) &&
                    ((state.dataRefrigCase->NumSimulationCases > 0) || (state.dataRefrigCase->NumSimulationWalkIns > 0))) {
                    state.dataHeatBal->RefrigCaseCredit(SuctionPipeActualZoneNum).SenCaseCreditToZone -= thisSys.PipeHeatLoad;
                } // UseSysTimeStep
            }
        } //(((.NOT. UseSysTimeStep).AND.(.NOT. System(SysNum)%CoilFlag)).OR.((UseSysTimeStep).AND.(System(SysNum)%CoilFlag)))
    } // SysNum

    // Need to know if mechanical subcoolers or cascade condensers or shared condensers
    //    are present. If so, energy transfer between
    //    detailed refrigeration systems requires additional iteration at this level.

    int StartMechSubcoolLoop(3); // if no mechanical subcoolers transfer energy between system,
    if ((state.dataRefrigCase->NumSimulationMechSubcoolers > 0) || (state.dataRefrigCase->NumSimulationCascadeCondensers > 0) ||
        (state.dataRefrigCase->NumSimulationSharedCondensers > 0) || (state.dataRefrigCase->NumSimulationRefrigAirChillers > 0)) {
        StartMechSubcoolLoop = 1;
    }

    bool FirstSCLoop = true; // Flag first time through multi-system loop used when mech subcoolers present

    for (int LoopNum = StartMechSubcoolLoop; LoopNum <= 3;
         ++LoopNum) { // Note, for cascade cond loads compared requiring 5 iterations to 3, no difference.

        for (int SysNum = 1; SysNum <= state.dataRefrigCase->NumRefrigSystems; ++SysNum) {
            auto &thisSys = System(SysNum);
            // Only do those systems appropriate for this analysis, supermarket type on load time step or coil type on sys time step
            if (((!state.dataRefrigCase->UseSysTimeStep) && (!thisSys.CoilFlag)) || ((state.dataRefrigCase->UseSysTimeStep) && (thisSys.CoilFlag))) {
                thisSys.SumMechSCLoad = 0.0;
                thisSys.SumCascadeLoad = 0.0;
                thisSys.SumCascadeCondCredit = 0.0;
                thisSys.SumMechSCBenefit = 0.0;

                if ((state.dataRefrigCase->NumSimulationMechSubcoolers > 0) && (!FirstSCLoop)) {
                    // This loop places load on system providing mechanical subcooling
                    for (int SubcoolID = 1; SubcoolID <= state.dataRefrigCase->NumSimulationSubcoolers; ++SubcoolID) {
                        if (Subcooler(SubcoolID).subcoolerType == SubcoolerType::LiquidSuction) {
                            continue;
                        }
                        if (Subcooler(SubcoolID).MechSourceSysID != SysNum) {
                            continue;
                        }
                        // don't have summechscload until second subcooler pass, set to zero on first pass
                        thisSys.SumMechSCLoad += thisSys.MechSCLoad(SubcoolID);
                        // subcooler should not drive Tevap for supplying system,
                        //    but check to see if T controlled can be met or if Tevap is at a higher temperature
                        if (Subcooler(SubcoolID).MechControlTliqOut < thisSys.TEvapNeeded) {
                            ShowWarningError(state, format("Refrigeration:System: {}", thisSys.Name));
                            ShowContinueError(state, " Evaporating temperature greater than the controlled ");
                            ShowContinueError(state, format(" liquid outlet temperature for SUBCOOLER:{}", Subcooler(SubcoolID).Name));
                        }
                    } // SubcoolId

                    if (thisSys.NumSubcoolers > 0) {
                        for (int SubcoolerIndex = 1; SubcoolerIndex <= thisSys.NumSubcoolers; ++SubcoolerIndex) {
                            int SubcoolID = thisSys.SubcoolerNum(SubcoolerIndex);
                            if (Subcooler(SubcoolID).subcoolerType == SubcoolerType::LiquidSuction) {
                                continue;
                            }
                            thisSys.SumMechSCBenefit = Subcooler(SubcoolID).MechSCTransLoad;
                        } // subcoolerindex
                    } // System(sysid)%numsubcoolers > 0
                } // NumSimulationMechSubcoolers > 0 and not first loop

                // This loop places load on system absorbing heat from cascade condenser and &
                //     condenser heat reclaim credits from hot gas/brine defrosts
                if ((thisSys.NumCascadeLoads > 0) && (!FirstSCLoop)) {
                    for (int CascadeLoadIndex = 1; CascadeLoadIndex <= thisSys.NumCascadeLoads; ++CascadeLoadIndex) {
                        int CascadeLoadID = thisSys.CascadeLoadNum(CascadeLoadIndex);
                        if (thisSys.CompSuctControl == CompressorSuctionPressureCtrl::ConstantSuctionTemperature) {
                            thisSys.TEvapNeeded = thisSys.TEvapDesign;
                        } else { // check for lowest T evap design among the CascadeLoad systems and
                            //  Compare Tevap for this Cascade to max allowed for cases, walk ins, and
                            //  for all previous CascadeLoad loops on this suction group and set
                            //  at the MINIMUM
                            if (Condenser(CascadeLoadID).CascadeTempControl == CascadeCndsrTempCtrlType::TempSet) {
                                // if float then set tevap based upon other loads
                                if (CascadeLoadIndex == 1 && thisSys.NumNonCascadeLoads == 0) {
                                    thisSys.TEvapNeeded = Condenser(CascadeLoadID).CascadeRatedEvapTemp;
                                } else {
                                    thisSys.TEvapNeeded = min(Condenser(CascadeLoadID).CascadeRatedEvapTemp, thisSys.TEvapNeeded);
                                }
                            }
                        } // floating or constant system evap temperature
                        // increment Cascade condenser Loads for Compressors/condenser on each system
                        // place any defrost credits on the same system absorbing the cascade condenser load
                        // (CascadeSysID identifies the condenser producing the defrost credits, that is, the lower temp system)
                        thisSys.SumCascadeLoad += Condenser(CascadeLoadID).CondLoad;
                        thisSys.SumCascadeCondCredit += System(Condenser(CascadeLoadID).CascadeSysID).TotalCondDefrostCredit;

                    } // NumCascadeLoads
                } // thisSys%NumCascadeLoads > 0

                // only calc detailed system if have load (could be zero first time through if only load is cascade condenser)
                thisSys.TotalSystemLoad = thisSys.TotalCoolingLoad + thisSys.SumSecondaryLoopLoad + thisSys.SumMechSCLoad + thisSys.SumCascadeLoad;
                if (thisSys.TotalSystemLoad > 0.0) {
                    thisSys.CpSatVapEvap = thisSys.refrig->getSatSpecificHeat(state, thisSys.TEvapNeeded, 1.0, RoutineName);
                    thisSys.HCaseOut =
                        thisSys.refrig->getSatEnthalpy(state, thisSys.TEvapNeeded, 1.0, RoutineName) + thisSys.CpSatVapEvap * CaseSuperheat;
                    // Establish estimates to start solution loop
                    switch (Condenser(thisSys.CondenserNum(1)).CondenserType) {
                    case DataHeatBalance::RefrigCondenserType::Air: {
                        thisSys.TCondense = state.dataEnvrn->OutDryBulbTemp + 16.7;
                        // 16.7C is delta T at rating point for air-cooled condensers, just estimate, so ok for zone-located condensers
                    } break;
                    case DataHeatBalance::RefrigCondenserType::Evap: {
                        thisSys.TCondense = state.dataEnvrn->OutDryBulbTemp + 15.0;
                        // 15C is delta T at rating point for evap-cooled condensers
                    } break;
                    case DataHeatBalance::RefrigCondenserType::Water: {
                        // define starting estimate at temperature of water exiting condenser
                        thisSys.TCondense = state.dataLoopNodes->Node(Condenser(thisSys.CondenserNum(1)).OutletNode).Temp;
                    } break;
                    case DataHeatBalance::RefrigCondenserType::Cascade: {
                        //?Don't need estimate for cascade condenser because it doesn't iterate?
                    } break;
                    default:
                        break;
                    }

                    // Produce first time step estimates, assume no subcoolers
                    thisSys.HSatLiqCond = thisSys.refrig->getSatEnthalpy(state, thisSys.TCondense, 0.0, RoutineName);
                    thisSys.CpSatLiqCond = thisSys.refrig->getSatSpecificHeat(state, thisSys.TCondense, 0.0, RoutineName);
                    thisSys.HCaseIn = thisSys.HSatLiqCond - thisSys.CpSatLiqCond * Condenser(thisSys.CondenserNum(1)).RatedSubcool;
                    thisSys.RefMassFlowtoLoads = thisSys.TotalSystemLoad / (thisSys.HCaseOut - thisSys.HCaseIn);
                    thisSys.RefMassFlowComps = thisSys.RefMassFlowtoLoads;

                    if (thisSys.NumStages == 2) { // Two-stage compression system
                        // Initial guess for high-stage mass flow rate in two-stage compression systems
                        thisSys.RefMassFlowHiStageComps = thisSys.RefMassFlowComps / 0.65;
                    }

                    thisSys.CalcDetailedSystem(state, SysNum);

                    bool DeRate; // If true, need to derate aircoils because load can't be met by system

                    // With air chiller coils, don't use unmet energy, instead reduce capacity on coils to match avail compressor/cond capacity
                    // current loads on compressor, exclusive of unmet loads from prev time steps
                    Real64 CurrentLoads = thisSys.TotalSystemLoad + thisSys.LSHXTrans; // because compressor capacity rated from txv to comp inlet
                    if ((thisSys.CoilFlag) && (CurrentLoads > (thisSys.TotCompCapacity * 1.001))) {
                        DeRate = true;
                        FinalRateCoils(state, DeRate, SourceType::DetailedSystem, SysNum, CurrentLoads, thisSys.TotCompCapacity);
                        thisSys.TotalCoolingLoad = 0.0;
                        thisSys.TotalCondDefrostCredit = 0.0;
                        for (int CoilIndex = 1; CoilIndex <= thisSys.NumCoils; ++CoilIndex) {
                            int CoilID = thisSys.CoilNum(CoilIndex);
                            // already CALLed CalculateCoil(CoilID) in CoilSet specified order
                            if (thisSys.CompSuctControl == CompressorSuctionPressureCtrl::ConstantSuctionTemperature) {
                                thisSys.TEvapNeeded = thisSys.TEvapDesign;
                            } else { // calculate floating T evap
                                thisSys.TEvapNeeded = thisSys.TEvapDesign;
                                ShowWarningError(state, format("Refrigeration:System: {}", thisSys.Name));
                                ShowContinueError(state, " Floating evaporator temperature model not yet available for warehouse coil systems. ");
                            } // floating or constant evap temperature
                            // increment TotalCoolingLoad for Compressors/condenser on each system
                            thisSys.TotalCoolingLoad += WarehouseCoil(CoilID).TotalCoolingLoad;
                            thisSys.TotalCondDefrostCredit += WarehouseCoil(CoilID).HotDefrostCondCredit;
                        } // NumCoils systems
                        if (thisSys.NumStages == 2 &&
                            thisSys.TotHiStageCompCapacity < (thisSys.TotalCoolingLoad + thisSys.LSHXTrans + thisSys.TotCompPower)) {
                            ShowRecurringWarningErrorAtEnd(state,
                                                           "Refrigeration:System: " + thisSys.Name +
                                                               ":The specified high-stage compressors for this system are unable to meet the sum "
                                                               "of the refrigeration loads, ",
                                                           thisSys.HiStageWarnIndex1);
                            ShowRecurringContinueErrorAtEnd(
                                state, " subcooler loads (if any), and low-stage compressor loads for this system.", thisSys.HiStageWarnIndex2);
                        } // Hi-stage capacity<(load+LSHX load + lo-stage compressor load)
                    } // CoilFlag (Numcoils > 0) and load > capacity

                } // thisSys%TotalSystemLoad > 0
            } //(((.NOT. UseSysTimeStep).AND.(.NOT. thisSys%CoilFlag)).OR.((UseSysTimeStep).AND.(thisSys%CoilFlag)))
        } // SysNum over NumRefrigSystems
        FirstSCLoop = false;
    } // LoopNum, three times for buildings with multiple detailed systems connected with mechanical subcoolers
    // or cascade condensers or shared condensers or warehouse coils that might need to be de-rated

    // Dealing with unmet load has to be done outside iterative loop
    for (int SysNum = 1; SysNum <= state.dataRefrigCase->NumRefrigSystems; ++SysNum) {
        auto &thisSys = System(SysNum);
        // Only do those systems appropriate for this analysis, supermarket type on load time step or coil type on sys time step
        if ((((!state.dataRefrigCase->UseSysTimeStep) && (!thisSys.CoilFlag)) || ((state.dataRefrigCase->UseSysTimeStep) && (thisSys.CoilFlag))) &&
            (!state.dataGlobal->WarmupFlag)) {
            Real64 CurrentLoads = thisSys.TotalSystemLoad + thisSys.LSHXTrans; // because compressor capacity rated from txv to comp inlet
            Real64 CurrentHiStageLoads(0.0); // Current loads on high-stage compressor, exclusive of unmet loads from
            if (thisSys.NumStages == 2) {
                CurrentHiStageLoads = CurrentLoads + thisSys.TotCompPower;
            } // NumStages==2
            if (thisSys.CoilFlag) {
                // don't use 'unmet energy' with air chillers, see 'derate'
                thisSys.UnmetEnergy = 0.0;
                thisSys.UnmetHiStageEnergy = 0.0;
            } else {
                // Meeting current and possibly some portion of the previously unmet energy
                // perhaps future interest in reporting percent of installed capacity used(or number of compressors) ?
                // If the system compressors were unable to meet the current loads, save energy to be met in succeeding time step
                // Note the unmet energy is turned into a rate and applied to the system load at the start of calccompressor
                thisSys.UnmetEnergy += (CurrentLoads - thisSys.TotCompCapacity) * state.dataGlobal->TimeStepZoneSec;
                if (thisSys.NumStages == 2) {
                    thisSys.UnmetHiStageEnergy += (CurrentHiStageLoads - thisSys.TotHiStageCompCapacity) * state.dataGlobal->TimeStepZoneSec;
                }
                if (thisSys.UnmetEnergy > MyLargeNumber) {
                    thisSys.UnmetEnergy = MyLargeNumber;
                    if (state.dataRefrigCase->ShowUnmetEnergyWarning(SysNum)) {
                        ShowWarningError(state, format("Refrigeration:System: {}", thisSys.Name));
                        ShowContinueError(state, " The specified compressors for this system are unable to meet ");
                        ShowContinueError(state, " the sum of the refrigerated case loads and subcooler loads (if any) for this system.");
                        state.dataRefrigCase->ShowUnmetEnergyWarning(SysNum) = false;
                    } // show warning
                } // > mylarge number
                if (thisSys.UnmetHiStageEnergy > MyLargeNumber) {
                    thisSys.UnmetHiStageEnergy = MyLargeNumber;
                    if (state.dataRefrigCase->ShowHiStageUnmetEnergyWarning(SysNum)) {
                        ShowWarningError(state, format("Refrigeration:System: {}", thisSys.Name));
                        ShowContinueError(state, " The specified high-stage compressors for this system are unable to meet ");
                        ShowContinueError(state, " the sum of the refrigerated case loads, subcooler loads (if any) and ");
                        ShowContinueError(state, " low-stage compressor loads for this system.");
                        state.dataRefrigCase->ShowHiStageUnmetEnergyWarning(SysNum) = false;
                    } // show warning
                } // > mylarge number
            } // numcoils > 0

            // Zone-located air-cooled condenser reject heat also has to be outside iterative loop
            if (thisSys.SystemRejectHeatToZone) {
                int CondInletAirZoneNum = Condenser(thisSys.CondenserNum(1)).InletAirZoneNum;
                if (state.dataRefrigCase->UseSysTimeStep) {
                    CoilSysCredit(CondInletAirZoneNum).SenCreditToZoneRate += thisSys.NetHeatRejectLoad; // Adding heat is positive
                    CoilSysCredit(CondInletAirZoneNum).ReportSenCoolingToZoneRate = -CoilSysCredit(CondInletAirZoneNum).SenCreditToZoneRate;
                }
                // Can arrive here when load call to refrigeration looks for cases/walkin systems and usetimestep is .FALSE.
                if ((!state.dataRefrigCase->UseSysTimeStep) &&
                    ((state.dataRefrigCase->NumSimulationCases > 0) || (state.dataRefrigCase->NumSimulationWalkIns > 0))) {
                    state.dataHeatBal->RefrigCaseCredit(CondInletAirZoneNum).SenCaseCreditToZone +=
                        thisSys.NetHeatRejectLoad; // Adding heat is positive
                } // UseSystimestep
            } // Reject heat to zone

            // Report variables
            thisSys.TotTransferLoad = thisSys.SumMechSCLoad - thisSys.SumMechSCBenefit + thisSys.SumSecondaryLoopLoad + thisSys.SumCascadeLoad;
            thisSys.TotTransferEnergy = thisSys.TotTransferLoad * localTimeStepSec;
            thisSys.PipeHeatEnergy = thisSys.PipeHeatLoad * localTimeStepSec;
            thisSys.TotalCoolingEnergy = thisSys.TotalCoolingLoad * localTimeStepSec;
        } //(((.NOT. UseSysTimeStep).AND.(.NOT. System(SysNum)%CoilFlag)).OR.((UseSysTimeStep).AND.(System(SysNum)%CoilFlag))).and.not
          // WarmupFlag
    } // SysNum = 1,NumRefrigSystems

    // Update for sending to zone equipment manager. (note report variables are summed elsewhere)
    //   LatOutputProvided = CoilSysCredit(ZoneNum)%LatKgPerS_ToZoneRate
    //   SysOutputProvided = CoilSysCredit(ZoneNum)%SenCreditToZoneRate
    // Note that case credit is negative for cooling, thus subtract positive value calculated for coil
    //   Note this is done whether or not the coils are derated.
    if (state.dataRefrigCase->UseSysTimeStep) {
        for (int ZoneNum = 1; ZoneNum <= state.dataGlobal->NumOfZones; ++ZoneNum) {
            auto &zoneCredit = CoilSysCredit(ZoneNum);
            for (int CoilID = 1; CoilID <= state.dataRefrigCase->NumSimulationRefrigAirChillers; ++CoilID) {
                auto &coil = WarehouseCoil(CoilID);
                if (coil.ZoneNum != ZoneNum) {
                    continue;
                }
                zoneCredit.SenCreditToZoneRate -= coil.SensCreditRate;
                zoneCredit.SenCreditToZoneEnergy = zoneCredit.SenCreditToZoneRate * localTimeStepSec;
                zoneCredit.LatKgPerS_ToZoneRate -= coil.LatKgPerS_ToZone;
                zoneCredit.LatCreditToZoneRate -= coil.LatCreditRate;
                zoneCredit.LatCreditToZoneEnergy -= coil.LatCreditEnergy;
            }
        }
    }

    SumZoneImpacts(state);
}

void SimulateDetailedTransRefrigSystems(EnergyPlusData &state)
{

    // SUBROUTINE INFORMATION:
    //       AUTHOR         Brian A. Fricke, ORNL
    //       DATE WRITTEN   Fall 2011
    //       RE-ENGINEERED  na

    // PURPOSE OF THIS SUBROUTINE:
    // This subroutine is called to simulate detailed transcritical CO2 refrigeration systems

    // METHODOLOGY EMPLOYED:
    // Each refrigeration system is modeled by first simulating the attached refrigerated cases and
    // walk-ins. The sum of the total heat transfer for all attached cases and walk-ins determines
    // the load on the compressors. Iterations are used here to account for sharing of gas coolers
    // between independent refrigeration systems.

    static constexpr std::string_view RoutineName = "SimulateDetailedTransRefrigSystems";

    auto &RefrigCase = state.dataRefrigCase->RefrigCase;
    auto &TransSystem = state.dataRefrigCase->TransSystem;
    auto &GasCooler = state.dataRefrigCase->GasCooler;
    auto &WalkIn = state.dataRefrigCase->WalkIn;

    Real64 localTimeStep = (state.dataRefrigCase->UseSysTimeStep) ? state.dataHVACGlobal->TimeStepSys : state.dataGlobal->TimeStepZone;
    Real64 localTimeStepSec = localTimeStep * Constant::rSecsInHour;

    //  Do transcritical CO2 refrigeration system loop outside of iterative solution to initialize time step and
    //  calculate case and and walk-ins (that won't change during balance of refrigeration system iterations)
    //  and prepare initial estimates for the iterative system solution

    //  TransCritSysFlag = .TRUE.
    for (auto &thisSys : TransSystem) {
        // Only do those systems appropriate for this analysis, supermarket type on load time step
        if (thisSys.NumCasesMT > 0) {
            for (int CaseIndex = 1; CaseIndex <= thisSys.NumCasesMT; ++CaseIndex) {
                int CaseID = thisSys.CaseNumMT(CaseIndex);
                RefrigCase(CaseID).CalculateCase(state);
                //  TEvapDesignMT calc in Get Input to meet lowest evap temp of any MT load on the system.
                //  TEvapNeededMT is fixed at this design value.
                thisSys.TEvapNeededMT = thisSys.TEvapDesignMT;
                // increment TotalCoolingLoad for Compressors/gas cooler on each system and defrost gas cooler credits for heat recovery
                thisSys.TotalCoolingLoadMT += RefrigCase(CaseID).TotalCoolingLoad;
                thisSys.TotalCondDefrostCredit += RefrigCase(CaseID).HotDefrostCondCredit;
            } // NumCasesMT
        } // Num of MT cases > 0

        if (thisSys.NumCasesLT > 0) {
            for (int CaseIndex = 1; CaseIndex <= thisSys.NumCasesLT; ++CaseIndex) {
                int CaseID = thisSys.CaseNumLT(CaseIndex);
                RefrigCase(CaseID).CalculateCase(state);
                //  TEvapDesignLT calc in Get Input to meet lowest evap temp of any LT load on the system.
                //  TEvapNeededLT is fixed at this design value.
                thisSys.TEvapNeededLT = thisSys.TEvapDesignLT;
                // increment TotalCoolingLoad for Compressors/gas cooler on each system and defrost gas cooler credits for heat recovery
                thisSys.TotalCoolingLoadLT += RefrigCase(CaseID).TotalCoolingLoad;
                thisSys.TotalCondDefrostCredit += RefrigCase(CaseID).HotDefrostCondCredit;
            } // NumCasesLT
        } // Num of LT cases > 0

        if (thisSys.NumWalkInsMT > 0) {
            for (int WalkInIndex = 1; WalkInIndex <= thisSys.NumWalkInsMT; ++WalkInIndex) {
                int WalkInID = thisSys.WalkInNumMT(WalkInIndex);
                WalkIn(WalkInID).CalculateWalkIn(state);
                //  TEvapDesignMT calc in Get Input to meet lowest evap temp of any MT load on the system.
                //  TEvapNeededMT is fixed at this design value.
                thisSys.TEvapNeededMT = thisSys.TEvapDesignMT;
                // increment TotalCoolingLoad for Compressors/gas cooler on each system
                thisSys.TotalCoolingLoadMT += WalkIn(WalkInID).TotalCoolingLoad;
                thisSys.TotalCondDefrostCredit += WalkIn(WalkInID).HotDefrostCondCredit;
            } // NumWalkInsMT systems
        } // thisSys%NumWalkInsMT > 0

        if (thisSys.NumWalkInsLT > 0) {
            for (int WalkInIndex = 1; WalkInIndex <= thisSys.NumWalkInsLT; ++WalkInIndex) {
                int WalkInID = thisSys.WalkInNumLT(WalkInIndex);
                WalkIn(WalkInID).CalculateWalkIn(state);
                //  TEvapDesignLT calc in Get Input to meet lowest evap temp of any LT load on the system.
                //  TEvapNeeded is fixed at this design value.
                thisSys.TEvapNeededLT = thisSys.TEvapDesignLT;
                // increment TotalCoolingLoad for Compressors/gas cooler on each system
                thisSys.TotalCoolingLoadLT += WalkIn(WalkInID).TotalCoolingLoad;
                thisSys.TotalCondDefrostCredit += WalkIn(WalkInID).HotDefrostCondCredit;
            } // NumWalkInsLT systems
        } // thisSys%NumWalkInsLT > 0

        // add suction pipe heat gains (W) if input by user
        // Suction pipe heat gains aren't included in the reported total system load, but are heat gains that must be met in
        //  gas cooler and compressor loads.
        thisSys.PipeHeatLoadMT = 0.0;
        if (thisSys.SumUASuctionPipingMT > MySmallNumber) {
            Real64 SuctionPipeZoneTemp = state.dataLoopNodes->Node(thisSys.SuctionPipeZoneNodeNumMT).Temp;
            thisSys.PipeHeatLoadMT = thisSys.SumUASuctionPipingMT * (SuctionPipeZoneTemp - thisSys.TEvapNeededMT);
            // pipe heat load is a positive number (ie. heat absorbed by pipe, so needs to be subtracted
            //   from refrigcasecredit (- for cooling zone, + for heating zone)
            int SuctionPipeActualZoneNum = thisSys.SuctionPipeActualZoneNumMT;
            // Can arrive here when load call to refrigeration looks for cases/walkin systems and usetimestep is .FALSE.
            if ((!state.dataRefrigCase->UseSysTimeStep) &&
                ((state.dataRefrigCase->NumSimulationCases > 0) || (state.dataRefrigCase->NumSimulationWalkIns > 0))) {
                state.dataHeatBal->RefrigCaseCredit(SuctionPipeActualZoneNum).SenCaseCreditToZone -= thisSys.PipeHeatLoadMT;
            } // UseSysTimeStep
        }

        thisSys.PipeHeatLoadLT = 0.0;
        if (thisSys.SumUASuctionPipingLT > MySmallNumber) {
            Real64 SuctionPipeZoneTemp = state.dataLoopNodes->Node(thisSys.SuctionPipeZoneNodeNumLT).Temp;
            thisSys.PipeHeatLoadLT = thisSys.SumUASuctionPipingLT * (SuctionPipeZoneTemp - thisSys.TEvapNeededLT);
            // pipe heat load is a positive number (ie. heat absorbed by pipe, so needs to be subtracted
            //   from refrigcasecredit (- for cooling zone, + for heating zone)
            int SuctionPipeActualZoneNum = thisSys.SuctionPipeActualZoneNumLT;
            // Can arrive here when load call to refrigeration looks for cases/walkin systems and usetimestep is .FALSE.
            if ((!state.dataRefrigCase->UseSysTimeStep) &&
                ((state.dataRefrigCase->NumSimulationCases > 0) || (state.dataRefrigCase->NumSimulationWalkIns > 0))) {
                state.dataHeatBal->RefrigCaseCredit(SuctionPipeActualZoneNum).SenCaseCreditToZone -= thisSys.PipeHeatLoadLT;
            } // UseSysTimeStep
        }

    } // SysNum

    // Need to know if shared gas coolers are present. If so, energy
    // transfer between detailed transcritical refrigeration systems
    // requires additional iteration at this level.

    int StartMechSubcoolLoop(3); // if no mechanical subcoolers transfer energy between system, don't loop
    if (state.dataRefrigCase->NumSimulationSharedGasCoolers > 0) {
        StartMechSubcoolLoop = 1;
    }

    for (int LoopNum = StartMechSubcoolLoop; LoopNum <= 3; ++LoopNum) {
        for (int SysNum = 1; SysNum <= state.dataRefrigCase->NumTransRefrigSystems; ++SysNum) {
            auto &sys = TransSystem(SysNum);
            // Only do those systems appropriate for this analysis, supermarket type on load time step or coil type on sys time step
            // only calc detailed system if have load
            sys.TotalSystemLoadMT = sys.TotalCoolingLoadMT;
            if (sys.transSysType == TransSysType::TwoStage) {
                sys.TotalSystemLoadLT = sys.TotalCoolingLoadLT;
            }
            sys.TotalSystemLoad = sys.TotalSystemLoadLT + sys.TotalSystemLoadMT;
            if (sys.TotalSystemLoad > 0.0) {
                if (sys.transSysType == TransSysType::TwoStage) {
                    sys.CpSatVapEvapLT = sys.refrig->getSatSpecificHeat(state, sys.TEvapNeededLT, 1.0, RoutineName);
                    sys.HCaseOutLT = sys.refrig->getSatEnthalpy(state, sys.TEvapNeededLT, 1.0, RoutineName) + sys.CpSatVapEvapLT * TransCaseSuperheat;
                }
                sys.CpSatVapEvapMT = sys.refrig->getSatSpecificHeat(state, sys.TEvapNeededMT, 1.0, RoutineName);
                sys.HCaseOutMT = sys.refrig->getSatEnthalpy(state, sys.TEvapNeededMT, 1.0, RoutineName) + sys.CpSatVapEvapMT * TransCaseSuperheat;

                // Produce first time step estimates.
                // Assume no subcoolers and neglect flow through bypass.
                sys.TReceiver = sys.refrig->getSatTemperature(state, sys.PReceiver, RoutineName);
                sys.HSatLiqReceiver = sys.refrig->getSatEnthalpy(state, sys.TReceiver, 0.0, RoutineName);
                sys.CpSatLiqReceiver = sys.refrig->getSatSpecificHeat(state, sys.TReceiver, 0.0, RoutineName);
                sys.HCaseInMT = sys.HSatLiqReceiver;
                sys.HCaseInLT = sys.HSatLiqReceiver;
                sys.RefMassFlowtoLTLoads = 0.0;
                sys.RefMassFlowCompsLP = 0.0;
                sys.DelHSubcoolerDis = 0.0;
                sys.DelHSubcoolerSuc = 0.0;
                if (sys.transSysType == TransSysType::TwoStage) {
                    sys.RefMassFlowtoLTLoads = sys.TotalSystemLoadLT / (sys.HCaseOutLT - sys.HCaseInLT);
                    sys.RefMassFlowCompsLP = sys.RefMassFlowtoLTLoads;
                } // (thisSys%TransSysType == 2)
                sys.RefMassFlowtoMTLoads = sys.TotalSystemLoadMT / (sys.HCaseOutMT - sys.HCaseInMT);
                sys.RefMassFlowCompsHP = sys.RefMassFlowtoLTLoads + sys.RefMassFlowtoMTLoads;

                sys.CalcDetailedTransSystem(state, SysNum);
                //       TransCritSysFlag = .FALSE.

            } // TransSystem(SysNum)%TotalSystemLoad > 0
        } // SysNum over NumRefrigSystems
    } // LoopNum, three times for buildings with multiple detailed systems connected with shared gas coolers

    // Unmet load is done outside iterative loop
    for (int SysNum = 1; SysNum <= state.dataRefrigCase->NumTransRefrigSystems; ++SysNum) {
        auto &sys = TransSystem(SysNum);
        // Only do those systems appropriate for this analysis, supermarket type on load time step or coil type on sys time step
        if ((!state.dataRefrigCase->UseSysTimeStep) && (!state.dataGlobal->WarmupFlag)) {
            Real64 CurrentLoads = sys.TotalSystemLoad;
            // Meeting current and possibly some portion of the previously unmet energy
            // perhaps future interest in reporting percent of installed capacity used(or number of compressors) ?
            // If the system compressors were unable to meet the current loads, save energy to be met in succeeding time step
            // Note the unmet energy is turned into a rate and applied to the system load at the start of calccompressor
            sys.UnmetEnergy += (CurrentLoads - sys.TotCompCapacity) * state.dataGlobal->TimeStepZoneSec;

            if (sys.UnmetEnergy > MyLargeNumber) {
                sys.UnmetEnergy = MyLargeNumber;
                if (state.dataRefrigCase->ShowUnmetEnergyWarningTrans(SysNum)) {
                    ShowWarningError(state, format("Refrigeration:TranscriticalSystem: {}", sys.Name));
                    ShowContinueError(state, " The specified compressors for this system are unable to meet ");
                    ShowContinueError(state, " the sum of the refrigerated case loads and subcooler loads (if any) for this system.");
                    state.dataRefrigCase->ShowUnmetEnergyWarningTrans(SysNum) = false;
                } // show warning
            } // > mylarge number

            // Zone-located air-cooled gas cooler reject heat also has to be outside iterative loop
            if (sys.SystemRejectHeatToZone) {
                int CondInletAirZoneNum = GasCooler(sys.GasCoolerNum(1)).InletAirZoneNum;
                // Can arrive here when load call to refrigeration looks for cases/walkin systems and usetimestep is .FALSE.
                if ((!state.dataRefrigCase->UseSysTimeStep) &&
                    ((state.dataRefrigCase->NumSimulationCases > 0) || (state.dataRefrigCase->NumSimulationWalkIns > 0))) {
                    state.dataHeatBal->RefrigCaseCredit(CondInletAirZoneNum).SenCaseCreditToZone += sys.NetHeatRejectLoad; // Adding heat is positive
                } // UseSystimestep
            } // Reject heat to zone

            // Report variables
            sys.PipeHeatEnergy = (sys.PipeHeatLoadMT + sys.PipeHeatLoadLT) * localTimeStepSec;
            sys.TotalCoolingEnergy = (sys.TotalCoolingLoadMT + sys.TotalCoolingLoadMT) * localTimeStepSec;
        } //(.NOT. UseSysTimeStep).AND. (.not. WarmupFlag)
    } // SysNum = 1,NumTransRefrigSystems

    // Update for sending to zone equipment manager. (note report variables are summed elsewhere)

    SumZoneImpacts(state);
}

void RefrigSystemData::CalcDetailedSystem(EnergyPlusData &state, int const SysNum)
{

    // SUBROUTINE INFORMATION:
    //       AUTHOR         Therese Stovall, ORNL, Assisted by Hugh Henderson
    //       DATE WRITTEN   Spring 2008
    //       Using condenser solution algorithms written by Richard Raustad, FSEC
    //          Oct/Nov 2004, and MODIFIED by Shirey, FSEC Dec 2004, and Hudson, ORNL in 2007
    //       RE-ENGINEERED  na

    // PURPOSE OF THIS SUBROUTINE:
    // Find the power and energy needed to meet the refrigeration loads for a particular detailed
    // refrigeration system comprised of multiple cases, one condenser, and multiple compressors.

    // METHODOLOGY EMPLOYED:
    // Sum the refrigeration loads on the system and determine the required evaporating temperature.
    // Using the initial estimate for condensing temperature, dispatch the compressors to
    // determine the needed power, energy consumption, and refrigerant mass flow.
    // Calculate the condenser fan/pump power and consumption.
    // Calculate the condensing temperature as a function of environment and load.
    // Resolve the impact of subcooler heat transfer between and among systems
    // Iterate until the calculated refrigerant mass flow through the compressors converges, which
    // typically requires less than 5 iterations. This was found to be more sensitive than converging
    // upon the calculated condensing temperature.

    // REFERENCES:
    // "Impact of ASHRAE Standard 62-1989 on Florida Supermarkets",
    //  Florida Solar Energy Center, FSEC-CR-910-96, Final Report, Oct. 1996

    // Kyle A. Manske, Performance Optimization of Industrial Refrigeration Systems,
    //  A thesis submitted in partial fulfillment of the requirements for the degree of
    //  Master of Science, University of Wisconsin-Madison, 1999

    Real64 constexpr ErrorTol(0.001); // Iterative solution tolerance

    bool NotBalanced = true;
    int NumIter = 0;
    Real64 ErrorMassFlowComps(0.0);        // Error in calculated low stage compressor mass flow (single- or two-stage systems)
    Real64 ErrorMassFlowHiStageComps(0.0); // Error in calculated high-stage compressor mass flow (two-stage systems only)

    // Balance This Refrigeration System using calculated refrigerant flow
    Real64 MassFlowHiStageCompsStart(0.0); // Mass flow through high-stage compressors (two-stage systems only)

    while (NotBalanced) {
        // Set values for iteration convergence tolerance check
        ++NumIter;
        // Mass flow through (low-stage) compressors (single- or two-stage systems)
        Real64 MassFlowCompsStart = this->RefMassFlowComps;

        if (this->NumStages == 2) { // Two-stage systems
            MassFlowHiStageCompsStart = this->RefMassFlowHiStageComps;
        }

        if (this->NumSubcoolers > 0) {
            this->CalculateSubcoolers(state);
        }
        this->CalculateCompressors(state);
        this->CalculateCondensers(state, SysNum);
        this->RefMassFlowtoLoads = this->TotalSystemLoad / (this->HCaseOut - this->HCaseIn);
        if (NumIter < 2) {
            continue;
        }
        // Previously did error check on calculated Tcondense, but not sensitive enough
        if ((this->RefMassFlowtoLoads == 0.0) || (MassFlowCompsStart == 0.0)) { //.OR. (MassFlowCasesStart == 0.0)
            ShowWarningError(state, format("Refrigeration:System: {} showing zero refrigeration flow.", this->Name));
        } else {
            ErrorMassFlowComps = std::abs(MassFlowCompsStart - this->RefMassFlowComps) / MassFlowCompsStart;
            if (this->NumStages == 2) { // Two-stage systems
                ErrorMassFlowHiStageComps = std::abs(MassFlowHiStageCompsStart - this->RefMassFlowHiStageComps) / MassFlowCompsStart;
            }
        } // denominator zero check
        if (NumIter > 20) {
            break;
        }
        if (ErrorMassFlowComps < ErrorTol) {
            if (this->NumStages == 1 || (this->NumStages == 2 && ErrorMassFlowHiStageComps < ErrorTol)) {
                NotBalanced = false;
            }
        }
    } // error check
}

void TransRefrigSystemData::CalcDetailedTransSystem(EnergyPlusData &state, int const SysNum)
{

    // SUBROUTINE INFORMATION:
    //       AUTHOR         Brian A. Fricke, ORNL
    //       DATE WRITTEN   Fall 2011
    //       MODIFIED       na
    //       RE-ENGINEERED  na

    // PURPOSE OF THIS SUBROUTINE:
    // Find the power and energy needed to meet the refrigeration loads for a detailed transcritical
    // CO2 refrigeration system comprised of multiple cases and walk-ins, one gas cooler, and
    // multiple compressors.

    // METHODOLOGY EMPLOYED:
    // Sum the refrigeration loads on the system and determine the required evaporating temperature.
    // Dispatch the compressors to determine the needed power, energy consumption, and refrigerant
    // mass flow. Calculate the gas cooler fan power and consumption. Calculate the gas cooler
    // outlet temperature and pressure as a function of ambient temperature. Iterate until the
    // calculated refrigerant mass flow through the receiver bypass converges, which typically
    // requires less than 5 iterations.

    Real64 constexpr ErrorTol(0.001); // Iterative solution tolerance

    int NumIter(0);            // Iteration counter
    bool NotBalanced(true);    // Flag to indicate convergence, based on system balance
    Real64 MassFlowStart(0.5); // Initial refrigerant mass flow through receiver bypass
    Real64 ErrorMassFlow;      // Error in calculated refrigerant mass flow through receiver bypass

    while (NotBalanced) {
        ++NumIter;

        if (this->NumGasCoolers >= 1) {
            this->CalcGasCooler(state, SysNum);
        }
        this->CalculateTransCompressors(state);
        if (NumIter < 2) {
            continue;
        }
        if ((this->RefMassFlowReceiverBypass == 0.0) || (MassFlowStart == 0.0)) {
            ShowSevereError(state,
                            format("Refrigeration:TranscriticalSystem: {} showing zero refrigerant flow through receiver bypass.", this->Name));
            ShowContinueError(state, format("Receiver Bypass Flow = {:.6R}", this->RefMassFlowReceiverBypass));
            ShowContinueError(state, "Check input file to ensure that refrigeration loads on this system are not zero.");
        } else {
            ErrorMassFlow = std::abs(MassFlowStart - this->RefMassFlowReceiverBypass) / MassFlowStart;
            MassFlowStart = this->RefMassFlowReceiverBypass;
        } // denominator zero check
        if (NumIter > 20) {
            break;
        }
        if (ErrorMassFlow < ErrorTol) {
            NotBalanced = false;
        }
    } // error check
}

void RefrigSystemData::CalculateCondensers(EnergyPlusData &state, int const SysNum)
{

    // SUBROUTINE INFORMATION:
    //       AUTHOR         Therese Stovall and C. R. Hudson, ORNL, Assisted by Hugh Henderson
    //       DATE WRITTEN   Spring 2008
    //       Using condenser solution algorithms written by Richard Raustad, FSEC
    //          Oct/Nov 2004, and MODIFIED by Shirey, FSEC Dec 2004, and Hudson, ORNL in 2007
    //       RE-ENGINEERED  na

    // PURPOSE OF THIS SUBROUTINE:
    // Find the condenser heat rejection for a particular detailed
    // refrigeration system and condensing temperature (part of iterative soln for cond temp).

    // METHODOLOGY EMPLOYED:
    // Calculate the condenser fan/pump power and consumption
    // using manufacturer's rating data and fan power correlations
    // from ASHRAE and evaporative effectiveness based on enthalpy
    // similar to work done by Manske.

    // From Heejin Cho, Re variable frequency drive fans,
    // "From HVAC forums, I learned that it is common practice to set a
    // minimum frequency at 15 or 20 Hz to protect motors from overheating. The
    // full speed is at 60 Hz. The ratio of minimum and maximum frequencies
    // will correspond to the ratio of minimum and maximum flow rates."

    // REFERENCES:
    // "Impact of ASHRAE Standard 62-1989 on Florida Supermarkets",
    //  Florida Solar Energy Center, FSEC-CR-910-96, Final Report, Oct. 1996

    // Kyle A. Manske, Performance Optimization of Industrial Refrigeration Systems,
    //  A thesis submitted in partial fulfillment of the requirements for the degree of
    //  Master of Science, University of Wisconsin-Madison, 1999

    // Lawrence Berkeley Laboratory and Resource Dynamics, Improving Fan System Performance,
    //   A Sourcebook for Industry, DOE/GO-102003-1294, April 2003

    Real64 constexpr BleedRateConstant = 5.0E-10; // water purge rate for evaporative
    //  condensers (m3/W-s) equal to 3 GPM per 100 tons (BAC Engineering Reference)

    auto &System = state.dataRefrigCase->System;
    auto &Condenser = state.dataRefrigCase->Condenser;

    int CondID;               // Condenser Number
    int CondCreditWarnIndex1; // Used to sum up warning count
    int CondCreditWarnIndex2; // Used to sum up warning count
    int CondCreditWarnIndex3; // Used to sum up warning count
    int CondCreditWarnIndex4; // Used to sum up warning count
    int CondCreditWarnIndex5; // Used to sum up warning count
    int CondCreditWarnIndex6; // Used to sum up warning count
    int CondCreditWarnIndex7; // Used to sum up warning count
    int Sysloop;              // counter over number of systems attached to this condenser
    int SystemID;             // System number rejecting heat to this condenser
    bool EvapAvail;           // Control for evap condenser availability

    Real64 AirVolRatio;                 // Ratio of air volume needed to remove load relative to design load
    Real64 AirDensity;                  // Density of air at condenser inlet [kg/m3]
    Real64 AirDensityDry;               // Density of dry air at condenser inlet temperature [kg/m3]
    Real64 ActualFanPower;              // Fan power after adjustments for partially loaded condenser [W]
    Real64 BPress;                      // Barometric pressure at condenser air inlet node [Pa]
    Real64 CapFac;                      // Capacity Factor
    Real64 Effectiveness;               // for evap condenser, =capacity/max cap, where max cap is cap if Tairout equal Tcondense
    Real64 EnthalpyAtTcond;             // enthalpy of saturated air at Tcondense
    Real64 EnthalpyAirIn;               // Enthalpy of air entering condenser [J/kg]
    Real64 EnthalpyAirOut;              // Enthalpy of air leaving condenser [J/kg]
    Real64 FanMinAirFlowRatio;          // Minimum fan air flow ratio
    Real64 FanPowerRatio;               // Calculated fan power ratio
    Real64 HRCF(0.0);                   // Heat Rejection Capacity Factor (convention for evap condensers)
    Real64 HRCFFullFlow;                // Heat Rejection Capacity Factor at full air flow
    Real64 HumRatIn;                    // Humidity ratio of inlet air to condenser [kg/kg]
    Real64 HumRatOut;                   // Humidity ratio of outlet air from condenser (assumed saturated) [kg/kg]
    Real64 OutWbTemp(0.0);              // Outdoor wet bulb temp at condenser air inlet node [C]
    Real64 OutDbTemp;                   // Outdoor dry bulb temp at condenser air inlet node [C]
    Real64 PurgeRate;                   // Rate of water blow-down/bleed/purge in evap condenser (m3/s)
    Real64 RatedFanPower;               // local variable equal to input condenser value
    Real64 RatedAirFlowRate;            // local variable equal to input condenser value
    Real64 SinkTemp;                    // Heat sink temperature used to derate fan power at reduced loads [C]
    Real64 TCondCalc;                   // Calculated Condensing temperature
    Real64 TotalCondDefrostCreditLocal; // total cond credit from hot gas/brine defr for cases etc. served
    //     directly by all systems served by this condenser [W]
    Real64 TotalCondDefCredfromSysID;    // cond credit for single system [W]
    Real64 TotalLoadFromThisSystem(0.0); // total heat rejection load from the detailed system id'd in subroutine call [W]
    Real64 TotalLoadFromSystems;         // total heat rejection load from all systems served by this condenser [W]

    Real64 localTimeStep = (state.dataRefrigCase->UseSysTimeStep) ? state.dataHVACGlobal->TimeStepSys : state.dataGlobal->TimeStepZone;
    Real64 localTimeStepSec = localTimeStep * Constant::rSecsInHour;

    // Initialize this condenser for this time step
    state.dataRefrigCase->TotalCondenserPumpPower = 0.0;
    state.dataRefrigCase->TotalBasinHeatPower = 0.0;
    state.dataRefrigCase->TotalCondenserHeat = 0.0;
    state.dataRefrigCase->TotalEvapWaterUseRate = 0.0;
    ActualFanPower = 0.0;
    TotalCondDefrostCreditLocal = 0.0;
    TotalLoadFromSystems = 0.0;
    EvapAvail = true;
    CondID = this->CondenserNum(1);
    auto &condenser = Condenser(CondID);
    RatedFanPower = condenser.RatedFanPower;
    RatedAirFlowRate = condenser.RatedAirFlowRate;
    FanMinAirFlowRatio = condenser.FanMinAirFlowRatio;
    CondCreditWarnIndex1 = condenser.CondCreditWarnIndex1;
    CondCreditWarnIndex2 = condenser.CondCreditWarnIndex2;
    CondCreditWarnIndex3 = condenser.CondCreditWarnIndex3;
    CondCreditWarnIndex4 = condenser.CondCreditWarnIndex4;
    CondCreditWarnIndex5 = condenser.CondCreditWarnIndex5;
    CondCreditWarnIndex6 = condenser.CondCreditWarnIndex6;
    CondCreditWarnIndex7 = condenser.CondCreditWarnIndex7;

    // Sum total condenser load and defrost credits for all systems connected to this condenser
    //  The system values will match the last time that system was solved, so some of the values may be
    //  from the previous overall solution iteration.  However, solution goes through 3 iterations if
    //  there are any shared condensers, so that's ok.
    for (Sysloop = 1; Sysloop <= condenser.NumSysAttach; ++Sysloop) {
        SystemID = condenser.SysNum(Sysloop);
        TotalCondDefCredfromSysID = System(SystemID).TotalCondDefrostCredit + System(SystemID).SumCascadeCondCredit;
        TotalCondDefrostCreditLocal += TotalCondDefCredfromSysID;
        // total heat rejection load from a single detailed system [W]
        Real64 TotalLoadFromSysID =
            System(SystemID).TotalSystemLoad + System(SystemID).TotCompPower + System(SystemID).TotHiStageCompPower + System(SystemID).PipeHeatLoad;
        TotalLoadFromSystems += TotalLoadFromSysID;
        if (SystemID == SysNum) {
            TotalLoadFromThisSystem = TotalLoadFromSysID;
        }
    } // Sysloop over every system connected to this condenser

    // for cascade condensers, condenser defrost credit gets passed on to the primary system condenser
    if (condenser.CondenserType == DataHeatBalance::RefrigCondenserType::Cascade) {
        TotalCondDefrostCreditLocal = 0.0;
    }

    // Calculate Total Heat rejection needed.  Assume hermetic compressors - conservative assumption
    // Note that heat rejection load carried by desuperheater hvac coils or water heaters is the
    // lagged variable from the previous time step because these are calculated after the refrigeration
    // system is solved.
    condenser.ExternalHeatRecoveredLoad = condenser.LaggedUsedWaterHeater + condenser.LaggedUsedHVACCoil;
    condenser.InternalHeatRecoveredLoad = TotalCondDefrostCreditLocal;
    condenser.TotalHeatRecoveredLoad = condenser.ExternalHeatRecoveredLoad + TotalCondDefrostCreditLocal;

    state.dataRefrigCase->TotalCondenserHeat = TotalLoadFromSystems - TotalCondDefrostCreditLocal - condenser.ExternalHeatRecoveredLoad;
    if (state.dataRefrigCase->TotalCondenserHeat < 0.0) {

        state.dataRefrigCase->TotalCondenserHeat = 0.0;
        if (!state.dataGlobal->WarmupFlag) {
            ShowRecurringWarningErrorAtEnd(state,
                                           "Refrigeration:System: " + this->Name +
                                               ":heat reclaimed(defrost,other purposes) >current condenser load. ",
                                           CondCreditWarnIndex1);
            ShowRecurringContinueErrorAtEnd(
                state, "For heat recovered for defrost: ASHRAE rule of thumb: <= 25% of the load on a rack ", CondCreditWarnIndex2);
            ShowRecurringContinueErrorAtEnd(
                state, "should be in defrost at the same time. Consider diversifying defrost schedules.", CondCreditWarnIndex3);
            ShowRecurringContinueErrorAtEnd(
                state,
                "For heat recovered for other purposes: this warning may be an artifact of refrigeration calculation at the load",
                CondCreditWarnIndex4);
            ShowRecurringContinueErrorAtEnd(
                state,
                "time step and heat recovery at the system time step. In that case, and ONLY if it occurs a large number of times",
                CondCreditWarnIndex5);
            ShowRecurringContinueErrorAtEnd(
                state, "(relative to the number of time steps in the simulation), there may be a mismatch between the", CondCreditWarnIndex6);
            ShowRecurringContinueErrorAtEnd(
                state, "operating schedules of the refrigeration system and the heat recovery load.", CondCreditWarnIndex7);
        } // not warmup
    } // total condenser heat < 0

    // Water side of water-cooled condensers simulated in SimRefrigCondenser,
    //   Here, we just need load and condensing temperatures.
    //   Condensing temperature a fixed delta (the rated approach temperature) from inlet water temp so long as above minimum.
    //   Note, if condensing temperature falls below minimum, get warning and reset but no change in water-side calculations.
    if (condenser.CondenserType == DataHeatBalance::RefrigCondenserType::Water) {
        // Obtain water-cooled condenser inlet/outlet temps
        condenser.InletTemp = state.dataLoopNodes->Node(condenser.InletNode).Temp;
        TCondCalc = state.dataLoopNodes->Node(condenser.InletNode).Temp + condenser.RatedApproachT;
        if ((condenser.InletTemp < condenser.InletTempMin) || (TCondCalc < this->TCondenseMin)) {
            this->TCondense = this->TCondenseMin;
            // condenser.LowTempWarn += 1;
            if (condenser.LowTempWarnIndex == 0) {
                ShowWarningMessage(state, format("Refrigeration:Condenser:WaterCooled {}", condenser.Name));
                ShowContinueError(state,
                                  "Water-cooled condenser inlet temp lower than minimum allowed temp. Check returning water temperature and/or "
                                  "minimum temperature setpoints relative to minimum allowed condensing temperature.");
            }
            ShowRecurringWarningErrorAtEnd(state,
                                           "Refrigeration:Condenser:WaterCooled " + condenser.Name +
                                               " - Condenser inlet temp lower than minimum allowed ... continues",
                                           condenser.LowTempWarnIndex);
            // END IF
        } else {
            this->TCondense = TCondCalc;
        }

    } else if ((condenser.CondenserType == DataHeatBalance::RefrigCondenserType::Air) ||
               (condenser.CondenserType == DataHeatBalance::RefrigCondenserType::Evap)) {
        // Condensing Temp, fan and other aux loads for air-cooled or evap-cooled

        // The rated capacity of air-cooled condenser was adjusted for elevation in get input step
        CapFac = state.dataRefrigCase->TotalCondenserHeat / condenser.RatedCapacity;
        // See whether condenser is at ground level or if other air conditions(ie node) have been specified.
        //    Note that air-cooled condensers can draw air from, and reject heat to, a conditioned zone
        //    But evaporative condensers cannot.
        // Provides effective condensing temperature for air-cooled condenser (or evap if evap is scheduled off)
        if (condenser.InletAirNodeNum != 0) {
            OutDbTemp = state.dataLoopNodes->Node(condenser.InletAirNodeNum).Temp;
            BPress = state.dataLoopNodes->Node(condenser.InletAirNodeNum).Press;
            HumRatIn = state.dataLoopNodes->Node(condenser.InletAirNodeNum).HumRat;
        } else {
            OutDbTemp = state.dataEnvrn->OutDryBulbTemp;
            BPress = state.dataEnvrn->OutBaroPress;
            HumRatIn = state.dataEnvrn->OutHumRat;
        }
        AirDensity = Psychrometrics::PsyRhoAirFnPbTdbW(state, BPress, OutDbTemp, HumRatIn);
        AirDensityDry = Psychrometrics::PsyRhoAirFnPbTdbW(state, BPress, OutDbTemp, 0.0);
        // Evaporative condensers will have their water flow shut off in cold months to avoid
        //  'spectacular' icing problems.  Ideally, the user will use the evaporative schedule input
        //  to set such a schedule.  However, sometimes, users will use a single input deck to model
        //  one building in multiple climates, and may not think to put in such a schedule in the colder
        //  climates.  To accommodate such applications, the variable EvapCutOutTdb is used as an extra
        //  check.

        if (OutDbTemp < EvapCutOutTdb) {
            EvapAvail = false;
        }

        // Check schedule to determine evap condenser availability
        // IF schedule exists, evap condenser can be scheduled OFF
        if ((condenser.CondenserType == DataHeatBalance::RefrigCondenserType::Evap) && (condenser.evapAvailSched != nullptr) &&
            (condenser.evapAvailSched->getCurrentVal() == 0)) {
            EvapAvail = false;
        }

        // Calculate condensing temperatures for air-cooled and evap-cooled
        if (condenser.CondenserType == DataHeatBalance::RefrigCondenserType::Evap) {
            // Manufacturer's HRCF regressed to produce a function of the form:
            // (Tcondense-Twb)=A1 + A2*hrcf + A3/hrcf + A4*Twb
            // HRCF defined as rated capacity divided by load
            // Apply ARI490 elevation correction factor here for evap condenser, then apply hrcf limits
            if (CapFac > 0.0) {
                HRCF = condenser.EvapElevFact / CapFac;
                // Condenser(CondNum)%EvapElevFact=1.0d0-3.074D-5*Elevation
            } else {
                HRCF = MyLargeNumber;
            }
            HRCF = min(HRCF, condenser.MaxCapFacEvap);
            HRCF = max(HRCF, condenser.MinCapFacEvap);
            if (EvapAvail) {
                OutWbTemp = Psychrometrics::PsyTwbFnTdbWPb(state, OutDbTemp, HumRatIn, BPress);
                SinkTemp = OutWbTemp;
            } else {         // evaporative condenser with water spray scheduled off so use Tdb
                HRCF /= 3.0; // reference Menske, cap of evap cond operating dry about 1/3 of rated cap
                HRCF = max(HRCF, condenser.MinCapFacEvap);
                SinkTemp = OutDbTemp;
            } // evap avail, still in evap condenser
            TCondCalc = condenser.EvapCoeff1 + condenser.EvapCoeff2 * HRCF + condenser.EvapCoeff3 / HRCF + (1.0 + condenser.EvapCoeff4) * SinkTemp;
        } else { // air-cooled condenser
            // MinCondLoad and TempSlope came from condenser capacity curve, using curve backwards
            TCondCalc = OutDbTemp + (state.dataRefrigCase->TotalCondenserHeat - condenser.MinCondLoad) * condenser.TempSlope;
            SinkTemp = OutDbTemp;
        } // if evap-cooled condenser

        // Fan energy calculations apply to both air- and evap-cooled condensers
        // Compare calculated condensing temps to minimum allowed to determine fan power/operating mode
        if (TCondCalc >= this->TCondenseMin) {
            this->TCondense = TCondCalc;
            ActualFanPower = RatedFanPower;
            AirVolRatio = 1.0;

        } else { // need to reduce fan speed to reduce air flow and keep Tcond at or above Tcond min
            this->TCondense = this->TCondenseMin;
            TCondCalc = this->TCondenseMin;
            // recalculate CapFac at current delta T
            if (condenser.CondenserType == DataHeatBalance::RefrigCondenserType::Air) {
                // current maximum condenser capacity at delta T present for minimum condensing temperature [W]
                Real64 CurMaxCapacity = Curve::CurveValue(state, condenser.CapCurvePtr, (this->TCondenseMin - OutDbTemp));
                CapFac = state.dataRefrigCase->TotalCondenserHeat / CurMaxCapacity;
                AirVolRatio = max(FanMinAirFlowRatio, std::pow(CapFac, CondAirVolExponentDry)); // Fans limited by minimum air flow ratio
                AirVolRatio = min(AirVolRatio, 1.0);
            } else { // condenser.CondenserType == DataHeatBalance::RefrigCondenserType::Evap
                HRCFFullFlow = HRCF;
                // if evap condenser need to back calculate the operating capacity using HRCF relationship, given known Tcond
                Real64 QuadBterm = condenser.EvapCoeff1 - (this->TCondense - SinkTemp) + condenser.EvapCoeff4 * SinkTemp;
                Real64 Sqrtterm = pow_2(QuadBterm) - 4.0 * condenser.EvapCoeff2 * condenser.EvapCoeff3;
                if (Sqrtterm < 0.0) { // only happens for very high wet bulb temps
                    HRCF = condenser.EvapElevFact * condenser.MaxCapFacEvap;
                    if (!EvapAvail) {
                        HRCF /= 3.0;
                    }
                    HRCF = max(HRCF, condenser.MinCapFacEvap);
                } else {
                    HRCF = condenser.EvapElevFact * (-QuadBterm - std::sqrt(Sqrtterm)) / (2.0 * condenser.EvapCoeff2);
                    if (!EvapAvail) {
                        HRCF /= 3.0;
                    }
                    HRCF = min(HRCF, condenser.MaxCapFacEvap);
                    HRCF = max(HRCF, condenser.MinCapFacEvap);
                } // sqrtterm
                CapFac = HRCF / HRCFFullFlow; // note, HRCFFullFlow previously limited between min and max,so can't be zero
                if (EvapAvail) {
                    AirVolRatio = max(FanMinAirFlowRatio, std::pow(CapFac, CondAirVolExponentEvap)); // Fans limited by minimum air flow ratio
                } else {                                                                             // evap not available
                    AirVolRatio = max(FanMinAirFlowRatio, std::pow(CapFac, CondAirVolExponentDry));  // Fans limited by minimum air flow ratio
                } // evap available
                AirVolRatio = min(AirVolRatio, 1.0);
            } // condenser type = DataHeatBalance::RefrigCondenserType::Air with else for evap

            switch (condenser.FanSpeedControlType) {
            case FanSpeedCtrlType::VariableSpeed: { // fan power law, adjusted for reality, applies
                FanPowerRatio = std::pow(AirVolRatio, 2.5);
                ActualFanPower = FanPowerRatio * RatedFanPower;
            } break;
            case FanSpeedCtrlType::ConstantSpeed: {
                ActualFanPower = AirVolRatio * std::exp(1.0 - AirVolRatio) * RatedFanPower;
            } break;
            case FanSpeedCtrlType::ConstantSpeedLinear: {
                ActualFanPower = AirVolRatio * RatedFanPower;
            } break;
            case FanSpeedCtrlType::TwoSpeed: {
                // low speed setting of 1/2 fan speed can give up to 60% of capacity.
                // 1/2 speed corresponds to ~1/8 power consumption (FanHalfSpeedRatio = 1/(2**2.5) = 0.1768)
                // dampers are used to control flow within those two ranges as in FanConstantSpeed
                Real64 const air_vol_fan_power_fac(std::exp(1.0 - AirVolRatio) * RatedFanPower);
                ActualFanPower = AirVolRatio * air_vol_fan_power_fac;
                if (CapFac < CapFac60Percent) {
                    ActualFanPower = ((AirVolRatio + 0.4) * FanHalfSpeedRatio) * air_vol_fan_power_fac;
                }
            } break;
            default:
                break;
            } // fan speed control type
        } // Tcondense >= Tcondense minimum

        if ((condenser.CondenserType == DataHeatBalance::RefrigCondenserType::Evap) && (EvapAvail)) {
            // calculate evap water use,  need to include bleed down/purge water as well as water
            // actually evaporated.  Use BAC Engineering Reference value of 3 gpm/100 tons because it's more
            // conservative than the ASHRAE value.
            //  Also, based on experience, running the evap water when outdoor T near freezing
            //  leads to 'spectacular' ice, so schedule evap off when Tdb <=4 C.
            // Calculate bleed/purge rate of water loss as a function of capacity, 3 gpm/100 tons refrigeration
            PurgeRate = state.dataRefrigCase->TotalCondenserHeat * BleedRateConstant;
            EnthalpyAirIn = Psychrometrics::PsyHFnTdbW(OutDbTemp, HumRatIn);
            // calculate effectiveness at rated conditions, so use Tcondcalc)
            EnthalpyAtTcond = Psychrometrics::PsyHFnTdbRhPb(state, TCondCalc, 1.0, BPress);
            Effectiveness = state.dataRefrigCase->TotalCondenserHeat / (RatedAirFlowRate * AirDensity * (EnthalpyAtTcond - EnthalpyAirIn));
            // need to limit max effectiveness for errors due to working beyond limits of HRCF in manuf data
            Effectiveness = min(Effectiveness, 0.9);
            EnthalpyAirOut = EnthalpyAirIn + Effectiveness * (EnthalpyAtTcond - EnthalpyAirIn);
            // Air leaving the evaporative condenser is saturated
            Real64 TAirOut = Psychrometrics::PsyTsatFnHPb(state, EnthalpyAirOut, BPress);
            HumRatOut = Psychrometrics::PsyWFnTdpPb(state, TAirOut, BPress);
            state.dataRefrigCase->TotalEvapWaterUseRate =
                PurgeRate + RatedAirFlowRate * AirVolRatio * AirDensityDry * (HumRatOut - HumRatIn) / Psychrometrics::RhoH2O(OutWbTemp);
            // assumes evap water pump runs whenever evap cooling is available to minimize scaling
            state.dataRefrigCase->TotalCondenserPumpPower = condenser.EvapPumpPower;
            // calculate basin water heater load
            if (state.dataRefrigCase->TotalCondenserHeat == 0.0 && OutDbTemp < condenser.BasinHeaterSetPointTemp) {
                state.dataRefrigCase->TotalBasinHeatPower =
                    max(0.0, condenser.BasinHeaterPowerFTempDiff * (condenser.BasinHeaterSetPointTemp - OutDbTemp));
                // provide warning if no heater power exists
                if (state.dataRefrigCase->TotalBasinHeatPower == 0.0) {
                    // condenser.EvapFreezeWarn = condenser.EvapFreezeWarn + 1;
                    if (condenser.EvapFreezeWarnIndex == 0) {
                        ShowWarningMessage(
                            state,
                            format("Refrigeration Condenser {} - Evap cooling of condenser underway with no basin heater power", condenser.Name));
                        ShowContinueError(state, "and condenser inlet air dry-bulb temp at or below the basin heater setpoint temperature.");
                        ShowContinueErrorTimeStamp(state, "Continuing simulation.");
                    }
                    ShowRecurringWarningErrorAtEnd(state,
                                                   "Refrigeration Condenser " + condenser.Name +
                                                       " - Evap cooling of condenser underway with no basin heater power ... continues",
                                                   condenser.EvapFreezeWarnIndex);
                    // END IF  !freeze warnings <= 5
                } // basin power == 0
            } // no load and cold outside
        } // EvapAvail

    } else if (condenser.CondenserType ==
               DataHeatBalance::RefrigCondenserType::Cascade) { // continuing Condenser type = water, (evap or air), or cascade
        // Cascade condenser does not iterate.  Condensing temperature specified as a load on higher temp system
        //    or floats to meet other loads on that system
        // therese ** future - here and for new phase change heat exchanger - need to handle unmet loads!

        this->TCondense = condenser.RatedTCondense;

        if ((this->NumNonCascadeLoads > 0) && (condenser.CascadeTempControl == CascadeCndsrTempCtrlType::TempFloat)) {
            this->TCondense = System(condenser.CascadeSinkSystemID).TEvapNeeded + condenser.RatedApproachT;
            if (this->TCondense < this->TCondenseMin) {
                this->TCondense = this->TCondenseMin;
                ShowRecurringWarningErrorAtEnd(state,
                                               "Refrigeration Condenser " + condenser.Name +
                                                   " - Cascade condenser floating condensing temperature less than specified minimum condensing "
                                                   "temperature. Minimum specified temperature used for system below cascade condenser. No "
                                                   "correction made for system absorbing heat rejected by the cascade condenser.",
                                               condenser.EvapFreezeWarnIndex);
            } // floating condensing temperature less than specified min for system
        } // floating temperature
    } // Condenser type = water, (evap or air), or cascade

    condenser.ActualFanPower = ActualFanPower;
    condenser.FanElecEnergy = ActualFanPower * localTimeStepSec;
    condenser.EvapWaterConsumpRate = state.dataRefrigCase->TotalEvapWaterUseRate;
    condenser.EvapWaterConsumption = state.dataRefrigCase->TotalEvapWaterUseRate * localTimeStepSec;
    condenser.ActualEvapPumpPower = state.dataRefrigCase->TotalCondenserPumpPower;
    condenser.EvapPumpConsumption = state.dataRefrigCase->TotalCondenserPumpPower * localTimeStepSec;
    condenser.BasinHeaterPower = state.dataRefrigCase->TotalBasinHeatPower;
    condenser.BasinHeaterConsumption = state.dataRefrigCase->TotalBasinHeatPower * localTimeStepSec;
    condenser.CondLoad = state.dataRefrigCase->TotalCondenserHeat;
    condenser.CondEnergy = state.dataRefrigCase->TotalCondenserHeat * localTimeStepSec;
    condenser.CondCreditWarnIndex1 = CondCreditWarnIndex1;
    condenser.CondCreditWarnIndex2 = CondCreditWarnIndex2;
    condenser.CondCreditWarnIndex3 = CondCreditWarnIndex3;
    condenser.CondCreditWarnIndex4 = CondCreditWarnIndex4;
    condenser.CondCreditWarnIndex5 = CondCreditWarnIndex5;
    condenser.CondCreditWarnIndex6 = CondCreditWarnIndex6;
    condenser.CondCreditWarnIndex7 = CondCreditWarnIndex7;
    condenser.ExternalEnergyRecovered = condenser.ExternalHeatRecoveredLoad * localTimeStepSec;
    condenser.InternalEnergyRecovered = condenser.InternalHeatRecoveredLoad * localTimeStepSec;
    condenser.TotalHeatRecoveredEnergy = condenser.TotalHeatRecoveredLoad * localTimeStepSec;
    this->NetHeatRejectLoad = state.dataRefrigCase->TotalCondenserHeat * TotalLoadFromThisSystem / TotalLoadFromSystems;
    this->NetHeatRejectEnergy = this->NetHeatRejectLoad * localTimeStepSec;

    // set water system demand request (if needed)
    if (condenser.EvapWaterSupplyMode == WaterSupply::FromTank) {
        state.dataWaterData->WaterStorage(condenser.EvapWaterSupTankID).VdotRequestDemand(condenser.EvapWaterTankDemandARRID) =
            condenser.EvapWaterConsumpRate;
    }
}

void TransRefrigSystemData::CalcGasCooler(EnergyPlusData &state, int const SysNum)
{

    // SUBROUTINE INFORMATION:
    //       AUTHOR         Brian A. Fricke, ORNL
    //       DATE WRITTEN   Fall 2011
    //       MODIFIED       na
    //       RE-ENGINEERED  na

    // PURPOSE OF THIS SUBROUTINE:
    // Find the gas cooler outlet temperature, the optimum gas cooler pressure, heat rejection,
    // fan power, and fan energy for a detailed transcritical CO2 refrigeration system.

    // METHODOLOGY EMPLOYED:
    // For a specified gas cooler outlet temperature in transcritical operation, there is an optimal gas cooler
    // pressure which produces the highest COP. A curve-fit equation similar to that presented by Ge and Tassou
    // (2011) and Sawalha (2008) is used to determine the optimum gas cooler pressure for a given gas cooler
    // outlet temperature. In subcritical operation, the condensing temperature and pressure are allowed to
    // float with ambient conditions, above the minimum condensing temperature.

    // REFERENCES:
    // Ge, Y.T., and S.A. Tassou. 2011. Performance evaluation and optimal design of supermarket refrigeration
    //     systems with supermarket model "SuperSim", Part I: Model description and validation. International
    //     Journal of Refrigeration 34: 527-539.
    // Ge, Y.T., and S.A. Tassou. 2011. Performance evaluation and optimal design of supermarket refrigeration
    //     systems with supermarket model "SuperSim", Part II: Model applications. International Journal of
    //     Refrigeration 34: 540-549.
    // Sawalha, S. 2008. Theoretical evaluation of trans-critical CO2 systems in supermarket refrigeration,
    //     Part I: Modeling, simulation and optimization of two system solutions. International Journal of
    //     Refrigeration 31: 516-524.
    // Sawalha, S. 2008. Theoretical evaluation of trans-critical CO2 systems in supermarket refrigeration,
    //     Part II: System modifications and comparisons of different solutions. International Journal of
    //     Refrigeration 31: 525-534.

    static constexpr std::string_view RoutineName = "RefrigeratedCase:CalcGasCooler";

    auto &TransSystem = state.dataRefrigCase->TransSystem;
    auto &GasCooler = state.dataRefrigCase->GasCooler;

    int GasCoolerCreditWarnIndex;       // Warning counter
    Real64 ActualFanPower;              // Fan power after adjustments for partially loaded gas cooler [W]
    Real64 AirVolRatio;                 // Ratio of air volume needed to remove load relative to design load
    Real64 FanMinAirFlowRatio;          // Minimum fan air flow ratio
    Real64 FanPowerRatio;               // Calculated fan power ratio
    Real64 OutDbTemp;                   // Outdoor dry bulb temperature at gas cooler air inlet node [C]
    Real64 RatedFanPower;               // Rated fan power for this gas cooler [W]
    Real64 TotalCondDefCredfromSysID;   // Gas cooler defrost credit for single system [W]
    Real64 TotalCondDefrostCreditLocal; // Total gas cooler credit from hot gas/brine defrost for cases etc. served
    //     directly by all systems served by this gas cooler [W]
    Real64 TotalGasCoolerHeat;           // Total gas cooler heat from system [W]
    Real64 TotalLoadFromSysID;           // Total heat rejection load from a single detailed system [W]
    Real64 TotalLoadFromSystems;         // Total heat rejection load from all systems served by this condenser [W]
    Real64 TotalLoadFromThisSystem(0.0); // Total heat rejection load from the detailed system identified in subroutine call [W]

    Real64 localTimeStep = (state.dataRefrigCase->UseSysTimeStep) ? state.dataHVACGlobal->TimeStepSys : state.dataGlobal->TimeStepZone;
    Real64 localTimeStepSec = localTimeStep * Constant::rSecsInHour;

    // Initialize this gas cooler for this time step
    ActualFanPower = 0.0;
    TotalCondDefrostCreditLocal = 0.0;
    TotalLoadFromSystems = 0.0;
    int GasCoolerID = this->GasCoolerNum(1);
    auto &cooler = GasCooler(GasCoolerID);
    RatedFanPower = cooler.RatedFanPower;
    FanMinAirFlowRatio = cooler.FanMinAirFlowRatio;
    GasCoolerCreditWarnIndex = cooler.GasCoolerCreditWarnIndex;

    for (int Sysloop = 1; Sysloop <= cooler.NumSysAttach; ++Sysloop) {
        int SystemID = cooler.SysNum(Sysloop);
        TotalCondDefCredfromSysID = TransSystem(SystemID).TotalCondDefrostCredit;
        TotalCondDefrostCreditLocal += TotalCondDefCredfromSysID;
        TotalLoadFromSysID = TransSystem(SystemID).TotalSystemLoadLT + TransSystem(SystemID).TotalSystemLoadMT +
                             TransSystem(SystemID).TotCompPowerLP + TransSystem(SystemID).TotCompPowerHP + TransSystem(SystemID).PipeHeatLoadLT +
                             TransSystem(SystemID).PipeHeatLoadMT;
        TotalLoadFromSystems += TotalLoadFromSysID;
        if (SystemID == SysNum) {
            TotalLoadFromThisSystem = TotalLoadFromSysID;
        }
    } // Sysloop over every system connected to this gas cooler

    // Calculate Total Heat rejection needed.
    cooler.InternalHeatRecoveredLoad = TotalCondDefrostCreditLocal;
    cooler.TotalHeatRecoveredLoad = TotalCondDefrostCreditLocal;
    TotalGasCoolerHeat = TotalLoadFromSystems - TotalCondDefrostCreditLocal;

    if (TotalGasCoolerHeat < 0.0) {
        TotalGasCoolerHeat = 0.0;
        if (!state.dataGlobal->WarmupFlag) {
            ShowRecurringWarningErrorAtEnd(state,
                                           "Refrigeration:TranscriticalSystem: " + this->Name +
                                               ":heat reclaimed (defrost,other purposes) is greater than current gas cooler load. ASHRAE rule of "
                                               "thumb: <= 25% of the load on a system should be in defrost at the same time. Consider "
                                               "diversifying defrost schedules.",
                                           GasCoolerCreditWarnIndex);
        }
    } // total gas cooler heat < 0

    // The rated capacity of air-cooled gas cooler was adjusted for elevation in get input step
    Real64 CapFac = TotalGasCoolerHeat / cooler.RatedCapacity;
    // See whether gas cooler is at ground level or if other air conditions (ie node) have been specified.
    // Note that air-cooled gas coolers can draw air from, and reject heat to, a conditioned zone.
    if (cooler.InletAirNodeNum != 0) {
        OutDbTemp = state.dataLoopNodes->Node(cooler.InletAirNodeNum).Temp;
    } else {
        OutDbTemp = state.dataEnvrn->OutDryBulbTemp;
    }
    // Determine gas cooler outlet temperature and pressure
    // Transcritical:  Gas cooler outlet temperature based on ambient temperature and approach temperature.
    //                 Determine optimum gas cooler pressure to maximize COP.
    // Subcritical:  Allow condensing temperature and pressure to float between minimum condensing temperature and
    //               transition temperature.
    if (OutDbTemp > cooler.TransitionTemperature) { // Gas cooler in transcritical operation
        cooler.TGasCoolerOut = OutDbTemp + cooler.GasCoolerApproachT;
        cooler.PGasCoolerOut = 1.0e5 * (2.3083 * state.dataEnvrn->OutDryBulbTemp + 11.9);
        if (cooler.PGasCoolerOut < 7.5e6) { // Ensure gas cooler pressure is at least 7.5 MPa for transcritical operation
            cooler.PGasCoolerOut = 7.5e6;
        }
        cooler.HGasCoolerOut = this->refrig->getSupHeatEnthalpy(state, cooler.TGasCoolerOut, cooler.PGasCoolerOut, RoutineName);
        cooler.TransOpFlag = true;
    } else { // Gas cooler in subcritical operation
        cooler.TGasCoolerOut = OutDbTemp + cooler.SubcriticalTempDiff;
        if (cooler.TGasCoolerOut > 30.978) { //  Gas temperature should be less than critical temperature
            cooler.PGasCoolerOut = 7.2e6;    //  Fix the pressure to be subcritical
            cooler.TGasCoolerOut = this->refrig->getSatTemperature(state, cooler.PGasCoolerOut, RoutineName);
        } else if (cooler.TGasCoolerOut > cooler.MinCondTemp) { //  Allow condensing temperature to float above the minimum
            cooler.PGasCoolerOut = this->refrig->getSatPressure(state, cooler.TGasCoolerOut, RoutineName);
        } else { //  Don't allow condensing temperature to drop below minimum
            cooler.TGasCoolerOut = cooler.MinCondTemp;
            cooler.PGasCoolerOut = this->refrig->getSatPressure(state, cooler.TGasCoolerOut, RoutineName);
        }
        cooler.HGasCoolerOut = this->refrig->getSatEnthalpy(state, cooler.TGasCoolerOut, 0.0, RoutineName);
        cooler.TransOpFlag = false;
    } // (OutDbTemp > TransitionTemperature)

    if (cooler.TGasCoolerOut < 30.978) {
        cooler.CpGasCoolerOut = this->refrig->getSatSpecificHeat(state, cooler.TGasCoolerOut, 0.0, RoutineName);
    } else {
        cooler.CpGasCoolerOut = 0.0;
    }

    // Gas cooler fan energy calculations
    AirVolRatio = max(FanMinAirFlowRatio, std::pow(CapFac, CondAirVolExponentDry)); // Fans limited by minimum air flow ratio

    switch (cooler.FanSpeedControlType) {
    case FanSpeedCtrlType::VariableSpeed: { // fan power law, adjusted for reality, applies
        FanPowerRatio = std::pow(AirVolRatio, 2.5);
        ActualFanPower = FanPowerRatio * RatedFanPower;
    } break;
    case FanSpeedCtrlType::ConstantSpeed: {
        ActualFanPower = AirVolRatio * std::exp(1.0 - AirVolRatio) * RatedFanPower;
    } break;
    case FanSpeedCtrlType::ConstantSpeedLinear: {
        ActualFanPower = AirVolRatio * RatedFanPower;
    } break;
    case FanSpeedCtrlType::TwoSpeed: {
        // low speed setting of 1/2 fan speed can give up to 60% of capacity.
        // 1/2 speed corresponds to ~1/8 power consumption (FanHalfSpeedRatio = 1/(2**2.5) = 0.1768)
        // dampers are used to control flow within those two ranges as in FanConstantSpeed
        ActualFanPower = AirVolRatio * std::exp(1.0 - AirVolRatio) * RatedFanPower;
        if (CapFac < CapFac60Percent) {
            ActualFanPower = ((AirVolRatio + 0.4) * (FanHalfSpeedRatio)) * std::exp(1.0 - AirVolRatio) * RatedFanPower;
        }
    } break;
    default:
        break;
    } // fan speed control type

    cooler.ActualFanPower = ActualFanPower;
    cooler.FanElecEnergy = ActualFanPower * localTimeStepSec;
    cooler.GasCoolerLoad = TotalGasCoolerHeat;
    cooler.GasCoolerEnergy = TotalGasCoolerHeat * localTimeStepSec;
    cooler.GasCoolerCreditWarnIndex = GasCoolerCreditWarnIndex;
    cooler.InternalEnergyRecovered = cooler.InternalHeatRecoveredLoad * localTimeStepSec;
    cooler.TotalHeatRecoveredEnergy = cooler.TotalHeatRecoveredLoad * localTimeStepSec;
    this->NetHeatRejectLoad = TotalGasCoolerHeat * TotalLoadFromThisSystem / TotalLoadFromSystems;
    this->NetHeatRejectEnergy = this->NetHeatRejectLoad * localTimeStepSec;
}

void RefrigSystemData::CalculateCompressors(EnergyPlusData &state)
{

    // SUBROUTINE INFORMATION:
    //       AUTHOR         Therese Stovall, ORNL, Assisted by Hugh Henderson
    //       DATE WRITTEN   Spring 2008
    //       MODIFIED       Brian Fricke, ORNL, March 2012, added two-stage compression
    //       RE-ENGINEERED  na

    // PURPOSE OF THIS SUBROUTINE:
    // Find the Compressor power, energy, capacity, and efficiency for a particular detailed
    // refrigeration system.  Routine is capable of modeling single-stage and two-stage
    // compression refrigeration systems.

    // METHODOLOGY EMPLOYED:
    // USe ARI compressor performance curves, the evaporating temperature and condensing temperature

    // REFERENCES:
    // "Impact of ASHRAE Standard 62-1989 on Florida Supermarkets",
    //  Florida Solar Energy Center, FSEC-CR-910-96, Final Report, Oct. 1996

    // ARI Standard 540, 2004, Standard for Performance Rating of Positive Displacement Refrigerant
    //  Compressors and Compressor Units, Air-Conditioning & Refrigeration Institute,Arlington VA

    // SUBROUTINE PARAMETER DEFINITIONS:
    // Following constants approp for R22, R134a, R404a, R507, R410a, R407c, future allow input?
    //   May want to allow input to reflect larger pipes selected to reduce delta P and increase compressor efficiency.
    // NOTE, these DelT...Pipes reflect the decrease in Pressure in the pipes, NOT thermal transfer through the pipe walls.
    Real64 constexpr DelTSuctPipes(1.0);  // Tsat drop corresponding to P drop in suction pipes, ASHRAE 2006 p 2.4 (C)
    Real64 constexpr DelTDischPipes(0.5); // Tsat drop corresponding to P drop in discharge pipes, ASHRAE 2006 p 2.5 (C)

    static constexpr std::string_view RoutineName("RefrigeratedCase:CalculateCompressors");
    Real64 CaseEnthalpyChangeRated;   // Enthalpy change in cases at compressor rated cond, J/kg
    Real64 CapacityCorrection;        // Capacity at existing subcool/superheat over cap at rated conditions
    Real64 CpSatVapCondense;          // Specific heat of vapor at cond temp J/kg-C
    Real64 DensityRated;              // Density of inlet gas at rated superheat, m3/kg
    Real64 DensityActual;             // Density of superheated gas at compressor inlet, m3/kg
    Real64 HCompInRated(0.0);         // Enthalpy entering compressor at rated superheat, J/kg //Autodesk:Init
    Real64 HCaseInRated(0.0);         // Enthalpy entering cases at rated subcooling, J/kg //Autodesk:Init
    Real64 HSatVapCondense;           // Enthalpy of saturated vapor at T condense, J/kg
    Real64 HsatVaporforTevapneeded;   // Enthalpy saturated vapor at temperature needed at evaporator
    Real64 LFLastComp;                // Load factor for last compressor dispatched
    Real64 MassCorrection;            // Mass flow at existing subcool/superheat over cap at rated conditions
    Real64 NeededCapacity;            // Sum of case loads and mech subcooler loads on suction group
    Real64 PSuction;                  // Suction Pressure
    Real64 PCond;                     // Condensing pressure
    Real64 PEvap;                     // Evaporating pressure
    Real64 TCompOutEstimate;          // Estimated temperature out of the compressor, used to flag whether heat reclaim is reasonable, C
    Real64 TempInRated(0.0);          // Temperature entering compressor at rated superheat, C //Autodesk:Init
    Real64 TotalEnthalpyChangeActual; // Actual enthalpy change in cases and cold side of LSHX, J/kg
    Real64 TsatforPsuct;              // Tsat for PSuction, C
    Real64 TsatforPdisch(0.0);        // Tsat for Pdischarge, c
    int NumComps;                     // Number of low-stage or high-stage compressors in system
    Real64 HHiStageCompIn;            // Enthalpy at inlet of high-stage compressor (J/kg)
    Real64 HCaseInRated_base(0.0), HCompInRated_base(0.0); // Autodesk:Tuned Intermediate values for performance tuning

    auto &Condenser = state.dataRefrigCase->Condenser;
    auto &Compressor = state.dataRefrigCase->Compressor;

    Real64 localTimeStep = (state.dataRefrigCase->UseSysTimeStep) ? state.dataHVACGlobal->TimeStepSys : state.dataGlobal->TimeStepZone;
    Real64 localTimeStepSec = localTimeStep * Constant::rSecsInHour;

    int CondID = this->CondenserNum(1);
    auto const &Condenser1 = Condenser(CondID);
    Real64 const AccumLoad = max(0.0, (this->UnmetEnergy / localTimeStepSec)); // Load due to previously unmet compressor loads
    Real64 const NeededCapacity_base(this->TotalSystemLoad + AccumLoad + this->PipeHeatLoad + this->LSHXTrans);

    // Before dispatching compressors, zero sum of compressor outputs and zero each compressor
    this->TotCompCapacity = 0.0;
    this->RefMassFlowComps = 0.0;
    this->TotCompPower = 0.0;
    if (this->NumStages == 2) {
        this->TotHiStageCompCapacity = 0.0;
        this->RefMassFlowHiStageComps = 0.0;
        this->TotHiStageCompPower = 0.0;
    }

    for (int CompIndex = 1; CompIndex <= this->NumCompressors; ++CompIndex) {
        int CompID = this->CompressorNum(CompIndex);
        auto &compressor = Compressor(CompID);
        compressor.Power = 0.0;
        compressor.MassFlow = 0.0;
        compressor.Capacity = 0.0;
        compressor.ElecConsumption = 0.0;
        compressor.CoolingEnergy = 0.0;
        compressor.LoadFactor = 0.0;
    }
    if (this->NumStages == 2) {
        for (int CompIndex = 1; CompIndex <= this->NumHiStageCompressors; ++CompIndex) {
            int CompID = this->HiStageCompressorNum(CompIndex);
            auto &compressor = Compressor(CompID);
            compressor.Power = 0.0;
            compressor.MassFlow = 0.0;
            compressor.Capacity = 0.0;
            compressor.ElecConsumption = 0.0;
            compressor.CoolingEnergy = 0.0;
            compressor.LoadFactor = 0.0;
        }
    }

    // Determine properties at case inlet and compressor inlet
    for (int StageIndex = 1; StageIndex <= min(2, this->NumStages); ++StageIndex) {
        if (StageIndex == 1) {                                    // Do single-stage or low-stage calculations
            if (this->NumStages == 1) {                           // Single-stage system
                NeededCapacity = NeededCapacity_base;             // because compressor capacity rated from txv to comp inlet
                TsatforPdisch = this->TCondense + DelTDischPipes; // need (Psat of (Tcond + delT corresponding to delP disch Pipes))
                TsatforPsuct = this->TEvapNeeded - DelTSuctPipes; // need (Psat of (Tevap - delT corresponding to del P suct Pipes))
                HsatVaporforTevapneeded = this->refrig->getSatEnthalpy(state, this->TEvapNeeded, 1.0, RoutineName);
                this->HSatLiqCond = this->refrig->getSatEnthalpy(state, this->TCondense, 0.0, RoutineName);
                this->CpSatLiqCond = this->refrig->getSatSpecificHeat(state, this->TCondense, 0.0, RoutineName);
                // HCaseIn is a function of the condenser rated subcooling, not the compressor rated subcooling
                // TCompIn needs to include case superheat as well as Temp change from lshx subcoolers
                // Calculate both here unless set previously by subcooler subroutine
                // HCaseOut corresponds to (tevapneeded + case superheat)
                // future - visit how parameter 'casesuperheat' applies when using walk-ins or transfer loads
                if (this->NumSubcoolers == 0) { // No subcooler on this system
                    this->HCaseIn = this->HSatLiqCond - this->CpSatLiqCond * Condenser1.RatedSubcool;
                    this->TCompIn = this->TEvapNeeded + CaseSuperheat; //+
                    this->TLiqInActual = this->TCondense - Condenser1.RatedSubcool;
                    this->HCompIn = this->HCaseOut;
                } else { // subcooler subroutine has been called to calc TCompIn and HCaseIn
                    this->HCompIn = this->HCaseOut + this->CpSatVapEvap * (this->TCompIn - (this->TEvapNeeded + CaseSuperheat));
                } // whether or not subcooler routine used
                PSuction = this->refrig->getSatPressure(state, TsatforPsuct, RoutineName);
                NumComps = this->NumCompressors;
            } else { // Low-stage side of two-stage system
                PCond = this->refrig->getSatPressure(state, this->TCondense, RoutineName);
                PEvap = this->refrig->getSatPressure(state, this->TEvapNeeded, RoutineName);
                this->PIntercooler = std::sqrt(PCond * PEvap);
                this->TIntercooler = this->refrig->getSatTemperature(state, this->PIntercooler, RoutineName);
                NeededCapacity = NeededCapacity_base;                // because compressor capacity rated from txv to comp inlet
                TsatforPdisch = this->TIntercooler + DelTDischPipes; // need (Psat of (Tinter + delT corresponding to delP disch Pipes))
                TsatforPsuct = this->TEvapNeeded - DelTSuctPipes;    // need (Psat of (Tevap - delT corresponding to del P suct Pipes))
                HsatVaporforTevapneeded = this->refrig->getSatEnthalpy(state, this->TEvapNeeded, 1.0, RoutineName);
                this->HSatLiqCond = this->refrig->getSatEnthalpy(state, this->TCondense, 0.0, RoutineName);
                this->CpSatLiqCond = this->refrig->getSatSpecificHeat(state, this->TCondense, 0.0, RoutineName);
                // HCaseIn is a function of the condenser rated subcooling, not the compressor rated subcooling
                // TCompIn needs to include case superheat as well as Temp change from lshx subcoolers
                // Calculate both here unless set previously by subcooler subroutine
                // HCaseOut corresponds to (tevapneeded + case superheat)
                if (this->NumSubcoolers == 0) { // No subcooler on this system
                    if (this->intercoolerType == IntercoolerType::Flash) {
                        this->HCaseIn = this->refrig->getSatEnthalpy(state, this->TIntercooler, 0.0, RoutineName);
                        this->TLiqInActual = this->TIntercooler;
                    } else if (this->intercoolerType == IntercoolerType::ShellAndCoil) {
                        this->TLiqInActual = this->TCondense - Condenser1.RatedSubcool -
                                             this->IntercoolerEffectiveness * (this->TCondense - Condenser1.RatedSubcool - this->TIntercooler);
                        this->HCaseIn = this->HSatLiqCond - this->CpSatLiqCond * (this->TCondense - this->TLiqInActual);
                    } // IntercoolerType
                    this->TCompIn = this->TEvapNeeded + CaseSuperheat; //+
                    this->HCompIn = this->HCaseOut;
                } else { // subcooler subroutine has been called to calc TCompIn and HCaseIn
                    this->HCompIn = this->HCaseOut + this->CpSatVapEvap * (this->TCompIn - (this->TEvapNeeded + CaseSuperheat));
                } // whether or not subcooler routine used
                PSuction = this->refrig->getSatPressure(state, TsatforPsuct, RoutineName);
                NumComps = this->NumCompressors;
            } // NumStages
        } else { // Two-stage system, high-stage side
            NeededCapacity = NeededCapacity_base + this->TotCompPower;
            TsatforPdisch = this->TCondense + DelTDischPipes;
            TsatforPsuct = this->TIntercooler;
            HsatVaporforTevapneeded = this->refrig->getSatEnthalpy(state, this->TIntercooler, 1.0, RoutineName);
            //                HSatLiqCond = Fluid::GetSatEnthalpyRefrig(state, RefrigerantName, TCondense, 0.0, RefIndex,
            // RoutineName
            //);
            ////Autodesk:Tuned These don't change for 2nd stage
            //                CpSatLiqCond = Fluid::GetSatSpecificHeatRefrig(RefrigerantName, TCondense, 0.0, RefIndex,
            // RoutineName );
            ////Autodesk:Tuned These don't change for 2nd stage
            this->HCaseIn = this->HSatLiqCond - this->CpSatLiqCond * Condenser1.RatedSubcool;
            this->TCompIn = this->TIntercooler;
            //      System(SysNum)%TLiqInActual = System(SysNum)%TCondense-Condenser(System(SysNum)%CondenserNum(1))%RatedSubcool
            this->HCompIn = HsatVaporforTevapneeded;
            PSuction = this->refrig->getSatPressure(state, TsatforPsuct, RoutineName);
            NumComps = this->NumHiStageCompressors;
        } // StageIndex

        // dispatch compressors to meet load, note they were listed in compressor list in dispatch order
        DensityActual = this->refrig->getSupHeatDensity(state, this->TCompIn, PSuction, RoutineName); // Autodesk:Tuned Hoisted out of CompIndex loop
        TotalEnthalpyChangeActual = this->HCompIn - this->HCaseIn;                                    // Autodesk:Tuned Hoisted out of CompIndex loop
        if (this->NumStages == 2) {                                                                   // Autodesk:Tuned Hoisted out of CompIndex loop
            if (StageIndex == 1) {
                HCaseInRated_base = this->refrig->getSatEnthalpy(state, this->TIntercooler, 0.0, RoutineName);
            } else if (StageIndex == 2) {
                HCompInRated_base = this->refrig->getSatEnthalpy(state, this->TIntercooler, 1.0, RoutineName);
            }
        }
        for (int CompIndex = 1; CompIndex <= NumComps; ++CompIndex) {
            int CompID;
            if (StageIndex == 1) {
                CompID = this->CompressorNum(CompIndex);
            } else {
                CompID = this->HiStageCompressorNum(CompIndex);
            } // StageIndex
            auto &compressor = Compressor(CompID);

            // need to use indiv compressor's rated subcool and superheat to adjust capacity to actual conditions
            switch (compressor.SubcoolRatingType) {
            case CompRatingType::Subcooling: {
                if (this->NumStages == 1) { // Single-stage system
                    HCaseInRated = this->HSatLiqCond - this->CpSatLiqCond * compressor.RatedSubcool;
                } else if (this->NumStages == 2 && StageIndex == 1) { // Two-stage system, low-stage side
                    HCaseInRated = HCaseInRated_base - this->CpSatLiqCond * compressor.RatedSubcool;
                } else if (this->NumStages == 2 && StageIndex == 2) { // Two-stage system, high-stage side
                    HCaseInRated = this->HSatLiqCond - this->CpSatLiqCond * compressor.RatedSubcool;
                } // NumStages
            } break;
            case CompRatingType::LiquidTemperature: { // have rated liquid temperature stored in "RatedSubcool"
                if (this->NumStages == 1) {           // Single-stage system
                    HCaseInRated = this->HSatLiqCond - this->CpSatLiqCond * (this->TCondense - compressor.RatedSubcool);
                } else if (this->NumStages == 2 && StageIndex == 1) { // Two-stage system, low-stage side
                    HCaseInRated = HCaseInRated_base - this->CpSatLiqCond * (this->TIntercooler - compressor.RatedSubcool);
                } else if (this->NumStages == 2 && StageIndex == 2) { // Two-stage system, high-stage side
                    HCaseInRated = this->HSatLiqCond - this->CpSatLiqCond * (this->TCondense - compressor.RatedSubcool);
                } // NumStages
            } break;
            default:
                break;
            } // Compressor SubcoolRatingType
            switch (compressor.SuperheatRatingType) {
            case CompRatingType::Superheat: {
                if (this->NumStages == 1) { // Single-stage system
                    HCompInRated = HsatVaporforTevapneeded + this->CpSatVapEvap * compressor.RatedSuperheat;
                    TempInRated = this->TEvapNeeded + compressor.RatedSuperheat;
                } else if (this->NumStages == 2 && StageIndex == 1) { // Two-stage system, low-stage side
                    HCompInRated = HsatVaporforTevapneeded + this->CpSatVapEvap * compressor.RatedSuperheat;
                    TempInRated = this->TEvapNeeded + compressor.RatedSuperheat;
                } else if (this->NumStages == 2 && StageIndex == 2) { // Two-stage system, high-stage side
                    HCompInRated = HCompInRated_base + this->CpSatVapEvap * compressor.RatedSuperheat;
                    TempInRated = this->TIntercooler + compressor.RatedSuperheat;
                } // NumStages
            } break;
            case CompRatingType::ReturnGasTemperature: { // have rated compressor inlet temperature stored in "RatedSuperheat"
                if (this->NumStages == 1) {              // Single-stage system
                    TempInRated = compressor.RatedSuperheat;
                    HCompInRated = HsatVaporforTevapneeded + this->CpSatVapEvap * (TempInRated - this->TEvapNeeded);
                } else if (this->NumStages == 2 && StageIndex == 1) { // Two-stage system, low-stage side
                    TempInRated = compressor.RatedSuperheat;
                    HCompInRated = HsatVaporforTevapneeded + this->CpSatVapEvap * (TempInRated - this->TEvapNeeded);
                } else if (this->NumStages == 2 && StageIndex == 2) { // Two-stage system, high-stage side
                    TempInRated = compressor.RatedSuperheat;
                    HCompInRated = HsatVaporforTevapneeded + this->CpSatVapEvap * (TempInRated - this->TIntercooler);
                } // NumStages
            } break;
            default:
                break;
            } // Compressor SuperheatRatingType

            CaseEnthalpyChangeRated = HCompInRated - HCaseInRated;
            DensityRated = this->refrig->getSupHeatDensity(state, TempInRated, PSuction, RoutineName);
            //  Adjust capacity and mass flow to reflect the specific volume change due to superheating and
            //  the increase in capacity due to extra subcooling
            MassCorrection = DensityActual / DensityRated;
            CapacityCorrection = MassCorrection * TotalEnthalpyChangeActual / CaseEnthalpyChangeRated;
            compressor.Power = Curve::CurveValue(state, compressor.ElecPowerCurvePtr, TsatforPsuct, TsatforPdisch);
            compressor.Capacity = CapacityCorrection * Curve::CurveValue(state, compressor.CapacityCurvePtr, TsatforPsuct, TsatforPdisch);
            compressor.MassFlow = compressor.Capacity / TotalEnthalpyChangeActual;

            // calculate load factor for last compressor added
            // assumes either cycling or part load eff = full load eff for last compressor
            if (StageIndex == 1) { // Single-stage or low-stage compressors
                if ((this->TotCompCapacity + compressor.Capacity) >= NeededCapacity) {
                    LFLastComp = (NeededCapacity - this->TotCompCapacity) / compressor.Capacity;
                    compressor.Power *= LFLastComp;
                    compressor.MassFlow *= LFLastComp;
                    compressor.Capacity *= LFLastComp;
                    this->TotCompCapacity += compressor.Capacity;
                    this->RefMassFlowComps += compressor.MassFlow;
                    this->TotCompPower += compressor.Power;
                    compressor.ElecConsumption = compressor.Power * localTimeStepSec;
                    compressor.CoolingEnergy = compressor.Capacity * localTimeStepSec;
                    compressor.LoadFactor = LFLastComp;
                    break; // numcomps do
                } //>= needed capacity
                this->TotCompCapacity += compressor.Capacity;
                this->RefMassFlowComps += compressor.MassFlow;
                this->TotCompPower += compressor.Power;
                //>= needed capacity
            } else { // high-stage compressors (for two-stage systems only)
                if ((this->TotHiStageCompCapacity + compressor.Capacity) >= NeededCapacity) {
                    LFLastComp = (NeededCapacity - this->TotHiStageCompCapacity) / compressor.Capacity;
                    compressor.Power *= LFLastComp;
                    compressor.MassFlow *= LFLastComp;
                    compressor.Capacity *= LFLastComp;
                    this->TotHiStageCompCapacity += compressor.Capacity;
                    this->RefMassFlowHiStageComps += compressor.MassFlow;
                    this->TotHiStageCompPower += compressor.Power;
                    this->FlowRatioIntercooler = this->RefMassFlowComps / this->RefMassFlowHiStageComps;
                    compressor.ElecConsumption = compressor.Power * localTimeStepSec;
                    compressor.CoolingEnergy = compressor.Capacity * localTimeStepSec;
                    compressor.LoadFactor = LFLastComp;
                    break; // numcomps do
                } //>= needed capacity
                this->TotHiStageCompCapacity += compressor.Capacity;
                this->RefMassFlowHiStageComps += compressor.MassFlow;
                this->TotHiStageCompPower += compressor.Power;
                //>= needed capacity
            } // StageIndex
            compressor.ElecConsumption = compressor.Power * localTimeStepSec;
            compressor.CoolingEnergy = compressor.Capacity * localTimeStepSec;
            compressor.LoadFactor = 1.0;
        } // NumComps
    }

    // Calculate enthalpy at compressor discharge
    if (this->NumStages == 1) { // Single-stage or low-stage compressors
        this->HCompOut = this->HCompIn + this->TotCompPower / this->RefMassFlowComps;
        // error found 9/19/2011, was System(SysNum)%TotCompPower*LocalTimeStep*DataGlobals::SecInHour/System(SysNum)%RefMassFlowComps
    } else { // High-stage compressors (only for two-stage systems)
        HHiStageCompIn = this->refrig->getSatEnthalpy(state, this->TIntercooler, 1.0, RoutineName);
        this->HCompOut = HHiStageCompIn + this->TotHiStageCompPower / this->RefMassFlowHiStageComps;
    }

    // Calculate superheat energy available for desuperheaters
    HSatVapCondense = this->refrig->getSatEnthalpy(state, this->TCondense, 1.0, RoutineName);
    CpSatVapCondense = this->refrig->getSatSpecificHeat(state, this->TCondense, 1.0, RoutineName);
    if (this->NumStages == 1) { // Single-stage systems
        state.dataHeatBal->HeatReclaimRefrigCondenser(CondID).AvailCapacity = this->RefMassFlowComps * (this->HCompOut - HSatVapCondense);
    } else { // Two-stage systems
        state.dataHeatBal->HeatReclaimRefrigCondenser(CondID).AvailCapacity = this->RefMassFlowHiStageComps * (this->HCompOut - HSatVapCondense);
    } // NumStages

    // No function available to get Tout as f(Pout, Hout), so use estimate based on constant cp in superheat range...
    //  Use average of Tcondense and Tout of condenser as check for whether heat reclaim is reasonable.
    TCompOutEstimate = this->TCondense + (this->HCompOut - HSatVapCondense) / CpSatVapCondense;

    state.dataHeatBal->HeatReclaimRefrigCondenser(CondID).AvailTemperature = (TsatforPdisch + TCompOutEstimate) / 2.0;
    this->AverageCompressorCOP = this->TotCompCapacity / (this->TotCompPower + this->TotHiStageCompPower);
    this->TotCompElecConsump = this->TotCompPower * localTimeStepSec;
    if (this->NumStages == 2) {
        this->TotHiStageCompElecConsump = this->TotHiStageCompPower * localTimeStepSec;
        this->TotCompElecConsumpTwoStage = this->TotCompElecConsump + this->TotHiStageCompElecConsump;
    }
    this->TotCompCoolingEnergy = this->TotCompCapacity * localTimeStepSec;
    this->TotHiStageCompCoolingEnergy = this->TotHiStageCompCapacity * localTimeStepSec;
}

void TransRefrigSystemData::CalculateTransCompressors(EnergyPlusData &state)
{

    // SUBROUTINE INFORMATION:
    //       AUTHOR         Brian A. Fricke, ORNL
    //       DATE WRITTEN   Fall 2011
    //       RE-ENGINEERED  na

    // PURPOSE OF THIS SUBROUTINE:
    // Find the compressor power, energy, capacity, and efficiency for a detailed transcritical CO2
    // refrigeration system.

    // METHODOLOGY EMPLOYED:
    // Use AHRI compressor performance curves for subcritical compressor operation, AHRI-style compressor
    // performance curves for transcritical compressor operation, the evaporating temperature of the
    // medium- and low-temperature loads, and the gas cooler outlet conditions (temperature, pressure
    // and enthalpy).

    // REFERENCES:
    // ANSI/AHRI. 2004. Standard 540, Standard for Performance Rating of Positive Displacement Refrigerant
    //     Compressors and Compressor Units. Arlington, VA: Air-Conditioning, Heating, and Refrigeration
    //     Institute.
    // Ge, Y.T., and S.A. Tassou. 2011. Performance evaluation and optimal design of supermarket refrigeration
    //     systems with supermarket model "SuperSim", Part I: Model description and validation. International
    //     Journal of Refrigeration 34: 527-539.
    // Ge, Y.T., and S.A. Tassou. 2011. Performance evaluation and optimal design of supermarket refrigeration
    //     systems with supermarket model "SuperSim", Part II: Model applications. International Journal of
    //     Refrigeration 34: 540-549.
    // Sawalha, S. 2008. Theoretical evaluation of trans-critical CO2 systems in supermarket refrigeration,
    //     Part I: Modeling, simulation and optimization of two system solutions. International Journal of
    //     Refrigeration 31: 516-524.
    // Sawalha, S. 2008. Theoretical evaluation of trans-critical CO2 systems in supermarket refrigeration,
    //     Part II: System modifications and comparisons of different solutions. International Journal of
    //     Refrigeration 31: 525-534.

    // SUBROUTINE PARAMETER DEFINITIONS:
    // Following constants approp for R22, R134a, R404a, R507, R410a, R407c.
    // For the same pressure drop, CO2 has a corresponding temperature penalty 5 to 10 times smaller than
    // ammonia and R-134a (ASHRAE Handbook of Refrigeration, 2010, p. 3.7).  Ignore pressure drop for CO2 calculations.
    // NOTE, these DelT...Pipes reflect the decrease in Pressure in the pipes, NOT thermal transfer through the pipe walls.

    Real64 constexpr ErrorTol(0.001); // Iterative solution tolerance

    static constexpr std::string_view RoutineName("RefrigeratedCase:CalculateTransCompressors");
    int Iter;                           // Iteration counter
    Real64 CapacityCorrectionMT;        // Capacity at existing subcool/superheat over cap at rated conditions for MT loads
    Real64 CaseEnthalpyChangeRatedMT;   // Enthalpy change in medium temperature cases at compressor rated cond, J/kg
    Real64 CaseEnthalpyChangeRatedLT;   // Enthalpy change in low temperature cases at compressor rated cond, J/kg
    Real64 DensityActualLT;             // Density of superheated gas at LP compressor inlet, m3/kg
    Real64 DensityActualMT;             // Density of superheated gas at HP compressor inlet, m3/kg
    Real64 DensityRatedHP;              // Density of high pressure compressor inlet gas at rated superheat, m3/kg
    Real64 DensityRatedLP;              // Density of low pressure compressor inlet gas at rated superheat, m3/kg
    Real64 HCaseInRatedLT;              // Enthalpy entering low temperature cases at rated subcooling, J/kg
    Real64 HCaseInRatedMT;              // Enthalpy entering medium temperature cases at rated subcooling, J/kg
    Real64 HCompInRatedHP(0.0);         // Enthalpy entering high pressure compressor at rated superheat, J/kg
    Real64 HCompInRatedLP;              // Enthalpy entering low pressure compressor at rated superheat, J/kg
    Real64 HGCOutlet;                   // Enthalpy at gas cooler outlet, J/kg
    Real64 HIdeal;                      // Ideal enthalpy at subcooler (for 100% effectiveness)
    Real64 HsatLiqforTevapNeededMT;     // Enthalpy of saturated liquid at MT evaporator, J/kg
    Real64 HsatVaporforTevapneededMT;   // Enthalpy of saturated vapor at MT evaporator (transcritical cycle), J/kg
    Real64 HsatVaporforTevapneededLT;   // Enthalpy of saturated vapor at LT evaporator (transcritical cycle), J/kg
    Real64 LFLastComp;                  // Load factor for last compressor dispatched
    Real64 MassCorrectionLT;            // Mass flow at existing subcool/superheat over cap at rated conditions for LT loads
    Real64 MassCorrectionMT;            // Mass flow at existing subcool/superheat over cap at rated conditions for MT loads
    Real64 NeededCapacityLT;            // Sum of LT case loads and mech subcooler loads (transcritical cycle), W
    Real64 NeededCapacityMT;            // Sum of MT case loads and mech subcooler loads (transcritical cycle), W
    Real64 PSuctionLT;                  // Suction pressure in low temperature cases, Pa
    Real64 PSuctionMT;                  // Suction pressure in medium temperature cases, Pa
    Real64 PGCOutlet;                   // Gas cooler outlet pressure, Pa
    Real64 QualityReceiver(0.0);        // Refrigerant quality in the receiver
    Real64 SubcoolEffect;               // Heat exchanger effectiveness of the subcooler
    Real64 TempInRatedHP;               // Temperature entering high pressure compressor at rated superheat, C
    Real64 TempInRatedLP;               // Temperature entering low pressure compressor at rated superheat, C
    Real64 TsatforPdisLT;               // Low temperature saturated discharge temperature (transcritical cycle), C
    Real64 TsatforPdisMT;               // Medium temperature saturated discharge temperature (transcritical cycle), C
    Real64 TsatforPsucLT;               // Low temperature saturated suction temperature (transcritical cycle), C
    Real64 TsatforPsucMT;               // Medium temperature saturated suction temperature (transcritical cycle), C
    Real64 TSubcoolerColdIn;            // Suction gas temperature at the inlet of the subcooler, C
    Real64 TotalEnthalpyChangeActualLT; // Actual enthalpy change in LT cases, J/kg
    Real64 TotalEnthalpyChangeActualMT; // Actual enthalpy change in MT cases, J/kg
    Real64 TotalRefMassFlow;            // Total mass flow through high pressure side of system, kg/s
    Real64 Xu;                          // Initial upper guess for iterative search
    Real64 Xl;                          // Initial lower guess for iterative search
    Real64 Xnew(0.0);                   // New guess for iterative search

    auto &Compressor = state.dataRefrigCase->Compressor;
    auto &GasCooler = state.dataRefrigCase->GasCooler;

    Real64 localTimeStep = (state.dataRefrigCase->UseSysTimeStep) ? state.dataHVACGlobal->TimeStepSys : state.dataGlobal->TimeStepZone;
    Real64 localTimeStepSec = localTimeStep * Constant::rSecsInHour;

    // Determine refrigerating capacity needed
    // Load due to previously unmet low temperature compressor loads (transcritical system)
    Real64 AccumLoadLT;
    NeededCapacityLT = 0.0;
    if (this->transSysType == TransSysType::TwoStage) {
        AccumLoadLT = max(0.0, (this->UnmetEnergyLT / localTimeStep / Constant::rSecsInHour)); // localTimeStep / rSecsInHour?
        NeededCapacityLT = this->TotalSystemLoadLT + AccumLoadLT + this->PipeHeatLoadLT;
    } // (TransSystem(SysNum)%TransSysType == 2)

    // Load due to previously unmet medium temperature compressor loads (transcritical system)
    Real64 AccumLoadMT = max(0.0, (this->UnmetEnergyMT / localTimeStep / Constant::rSecsInHour));
    NeededCapacityMT = this->TotalSystemLoadMT + AccumLoadMT + this->PipeHeatLoadMT;

    // Determine refrigerant properties at receiver
    this->CpSatLiqReceiver = this->refrig->getSatSpecificHeat(state, this->TReceiver, 0.0, RoutineName);

    // Enthalpy at the receiver bypass, J/kg
    Real64 HReceiverBypass = this->refrig->getSatEnthalpy(state, this->TReceiver, 1.0, RoutineName);

    // Determine refrigerant properties at low temperature (LT) loads (if present)
    // Dispatch low pressure (LP) compressors as necessary
    if (this->transSysType == TransSysType::TwoStage) { // LT side of TwoStage transcritical system
        this->HCaseInLT = this->HSatLiqReceiver;
        // TCompInLP and HCompInLP include case superheat plus effect of suction line heat gain
        this->TCompInLP = this->TEvapNeededLT + TransCaseSuperheat + this->PipeHeatLoadLT / (this->CpSatVapEvapLT * this->RefMassFlowtoLTLoads);
        this->HCompInLP = this->HCaseOutLT + this->PipeHeatLoadLT / this->RefMassFlowtoLTLoads;
        TsatforPsucLT = this->TEvapNeededLT;
        TsatforPdisLT = this->TEvapNeededMT;
        HsatVaporforTevapneededLT = this->refrig->getSatEnthalpy(state, this->TEvapNeededLT, 1.0, RoutineName);
        HsatLiqforTevapNeededMT = this->refrig->getSatEnthalpy(state, this->TEvapNeededMT, 0.0, RoutineName);
        PSuctionLT = this->refrig->getSatPressure(state, TsatforPsucLT, RoutineName);
        DensityActualLT = this->refrig->getSupHeatDensity(state, this->TCompInLP, PSuctionLT, RoutineName);
        TotalEnthalpyChangeActualLT = this->HCompInLP - this->HCaseInLT;

        // Dispatch low pressure (LP) compressors
        // Before dispatching LP compressors, zero sum of compressor outputs and zero each compressor
        this->TotCompCapacityLP = 0.0;
        this->RefMassFlowCompsLP = 0.0;
        this->TotCompPowerLP = 0.0;

        for (int CompIndex = 1; CompIndex <= this->NumCompressorsLP; ++CompIndex) {
            int CompID = this->CompressorNumLP(CompIndex);
            Compressor(CompID).Power = 0.0;
            Compressor(CompID).MassFlow = 0.0;
            Compressor(CompID).Capacity = 0.0;
            Compressor(CompID).ElecConsumption = 0.0;
            Compressor(CompID).CoolingEnergy = 0.0;
            Compressor(CompID).LoadFactor = 0.0;
        }

        for (int CompIndex = 1; CompIndex <= this->NumCompressorsLP; ++CompIndex) {
            int CompID = this->CompressorNumLP(CompIndex);
            auto &compressor = Compressor(CompID);
            // need to use indiv compressor's rated subcool and superheat to adjust capacity to actual conditions
            switch (compressor.SubcoolRatingType) {
            case CompRatingType::Subcooling: {
                HCaseInRatedLT = HsatLiqforTevapNeededMT - this->CpSatLiqReceiver * compressor.RatedSubcool;
            } break;
            case CompRatingType::LiquidTemperature: { // have rated liquid temperature stored in "RatedSubcool"
                HCaseInRatedLT = this->refrig->getSatEnthalpy(state, compressor.RatedSubcool, 0.0, RoutineName);
            } break;
            default:
                break;
            }
            switch (compressor.SuperheatRatingType) {
            case CompRatingType::Superheat: {
                HCompInRatedLP = HsatVaporforTevapneededLT + this->CpSatVapEvapLT * compressor.RatedSuperheat;
                TempInRatedLP = this->TEvapNeededLT + compressor.RatedSuperheat;
            } break;
            case CompRatingType::ReturnGasTemperature: { // have rated compressor inlet temperature stored in
                                                         // "CompRatingType::Superheat"
                TempInRatedLP = compressor.RatedSuperheat;
                HCompInRatedLP = this->refrig->getSupHeatEnthalpy(state, compressor.RatedSuperheat, PSuctionLT, RoutineName);
            } break;
            default:
                break;
            }

            CaseEnthalpyChangeRatedLT = HCompInRatedLP - HCaseInRatedLT;
            DensityRatedLP = this->refrig->getSupHeatDensity(state, TempInRatedLP, PSuctionLT, RoutineName);

            //  Adjust capacity and mass flow to reflect the specific volume change due to superheating and
            //  the increase in capacity due to extra subcooling
            MassCorrectionLT = DensityActualLT / DensityRatedLP;
            // Capacity at existing subcool/superheat over cap at rated conditions for LT loads
            Real64 CapacityCorrectionLT = MassCorrectionLT * TotalEnthalpyChangeActualLT / CaseEnthalpyChangeRatedLT;
            compressor.Power = Curve::CurveValue(state, compressor.ElecPowerCurvePtr, TsatforPsucLT, TsatforPdisLT);
            compressor.Capacity = CapacityCorrectionLT * Curve::CurveValue(state, compressor.CapacityCurvePtr, TsatforPsucLT, TsatforPdisLT);
            compressor.MassFlow = compressor.Capacity / TotalEnthalpyChangeActualLT;
            compressor.ElecConsumption = compressor.Power * localTimeStepSec;
            compressor.CoolingEnergy = compressor.Capacity * localTimeStepSec;
            compressor.LoadFactor = 1.0;
            if ((this->TotCompCapacityLP + compressor.Capacity) >= NeededCapacityLT) {
                LFLastComp = (NeededCapacityLT - this->TotCompCapacityLP) / compressor.Capacity;
                compressor.Power *= LFLastComp;
                compressor.MassFlow *= LFLastComp;
                compressor.Capacity *= LFLastComp;
                this->TotCompCapacityLP += compressor.Capacity;
                this->RefMassFlowCompsLP += compressor.MassFlow;
                this->TotCompPowerLP += compressor.Power;
                compressor.ElecConsumption = compressor.Power * localTimeStepSec;
                compressor.CoolingEnergy = compressor.Capacity * localTimeStepSec;
                compressor.LoadFactor = LFLastComp;
                break;
            }
            this->TotCompCapacityLP += compressor.Capacity;
            this->RefMassFlowCompsLP += compressor.MassFlow;
            this->TotCompPowerLP += compressor.Power;

        } // NumCompressorsLP
        this->HCompOutLP = this->HCompInLP + this->TotCompPowerLP / this->RefMassFlowCompsLP;
    } // (TransSystem(SysNum)%TransSysType == 2)

    // Determine refrigerant properties at medium temperature (MT) loads
    // Dispatch high pressure (HP) compressors as necessary
    TsatforPsucMT = this->TEvapNeededMT;
    if (GasCooler(this->GasCoolerNum(1)).TransOpFlag) { // Transcritical system is operating in transcritical region
        HGCOutlet = GasCooler(this->GasCoolerNum(1)).HGasCoolerOut;
    } else { // Transcritical system is operating in subcritical region
        TsatforPdisMT = GasCooler(this->GasCoolerNum(1)).TGasCoolerOut;
    }
    PSuctionMT = this->refrig->getSatPressure(state, TsatforPsucMT, RoutineName);
    PGCOutlet = GasCooler(this->GasCoolerNum(1)).PGasCoolerOut;
    HsatVaporforTevapneededMT = this->refrig->getSatEnthalpy(state, this->TEvapNeededMT, 1.0, RoutineName);
    this->HCaseInMT = this->HSatLiqReceiver;
    // Enthalpy of refrigerant after leaving medium temperature loads and low pressure compressors

    // Combined enthalpy from the outlets of the LP compressor and MT loads, J/kg
    Real64 HCaseOutLTMT = (this->RefMassFlowtoLTLoads * this->HCompOutLP + this->RefMassFlowtoMTLoads * this->HCaseOutMT + this->PipeHeatLoadMT) /
                          (this->RefMassFlowtoLTLoads + this->RefMassFlowtoMTLoads);

    // Total refrigerant flow rate is total flow from LT and MT loads divided by (1-x) where x is the quality of the
    // refrigerant entering the receiver.  The receiver bypass flow rate is (x)*(Total Flow).
    // Iterate to find the quality of the refrigerant entering the receiver.
    Xu = 1.0; // upper bound on quality
    Xl = 0.0; // lower bound on quality
    if ((GasCooler(this->GasCoolerNum(1)).HGasCoolerOut + this->DelHSubcoolerDis) > this->HSatLiqReceiver) {
        for (Iter = 1; Iter <= 15; ++Iter) { // Maximum of 15 iterations to find receiver quality
            QualityReceiver = (Xu + Xl) / 2.0;
            Real64 Hnew = this->refrig->getSatEnthalpy(state, this->TReceiver, QualityReceiver, RoutineName);

            // estimated QualityReceiver is too high
            if (Hnew > (GasCooler(this->GasCoolerNum(1)).HGasCoolerOut + this->DelHSubcoolerDis)) {
                Xu = QualityReceiver;
            } else { // estimated QualityReceiver is too low
                Xl = QualityReceiver;
            }
            if (std::abs((Hnew - (GasCooler(this->GasCoolerNum(1)).HGasCoolerOut + this->DelHSubcoolerDis)) / Hnew) < ErrorTol) {
                break;
            }
        }
        TotalRefMassFlow = (this->RefMassFlowtoLTLoads + this->RefMassFlowtoMTLoads) / (1.0 - QualityReceiver);
        this->RefMassFlowReceiverBypass = QualityReceiver * TotalRefMassFlow;
    } else {
        this->RefMassFlowReceiverBypass = 0.0;
        TotalRefMassFlow = (this->RefMassFlowtoLTLoads + this->RefMassFlowtoMTLoads);
    } // %HGasCoolerOut > TransSystem(SysNum)%HSatLiqReceiver)

    this->HCompInHP = (HCaseOutLTMT * (this->RefMassFlowtoLTLoads + this->RefMassFlowtoMTLoads) + HReceiverBypass * this->RefMassFlowReceiverBypass) /
                      (this->RefMassFlowtoLTLoads + this->RefMassFlowtoMTLoads + this->RefMassFlowReceiverBypass);

    // Iterate to find the suction temperature entering subcooler
    Xl = this->refrig->getSatTemperature(state, PSuctionMT, RoutineName);
    Xu = Xl + 50.0;
    for (Iter = 1; Iter <= 15; ++Iter) { // Maximum of 15 iterations
        Xnew = (Xu + Xl) / 2.0;
        Real64 Hnew = this->refrig->getSupHeatEnthalpy(state, Xnew, PSuctionMT, RoutineName);
        if (Hnew > this->HCompInHP) { // xnew is too high
            Xu = Xnew;
        } else { // xnew is too low
            Xl = Xnew;
        }
        if (std::abs((Hnew - this->HCompInHP) / Hnew) < ErrorTol) {
            break;
        }
    }
    TSubcoolerColdIn = Xnew;

    // Modify receiver inlet enthalpy and HP compressor inlet enthalpy to account for subcooler
    HIdeal = this->refrig->getSupHeatEnthalpy(state, GasCooler(this->GasCoolerNum(1)).TGasCoolerOut, PSuctionMT, RoutineName);
    // Only use subcooler if suction gas inlet temperature less than gas cooler outlet temperature
    if (TSubcoolerColdIn < GasCooler(this->GasCoolerNum(1)).TGasCoolerOut) {
        SubcoolEffect = this->SCEffectiveness;
    } else {
        SubcoolEffect = 0.0;
    } // (TSubcoolerColdIn < GasCooler(SysNum)%TGasCoolerOut)
    this->DelHSubcoolerSuc = SubcoolEffect * (HIdeal - this->HCompInHP);
    this->HCompInHP += this->DelHSubcoolerSuc;
    this->DelHSubcoolerDis = -this->DelHSubcoolerSuc;

    // Iterate to find the temperature at the inlet of the high pressure (HP) compressors
    Xl = this->refrig->getSatTemperature(state, PSuctionMT, RoutineName);
    Xu = Xl + 50.0;
    for (Iter = 1; Iter <= 15; ++Iter) { // Maximum of 15 iterations
        Xnew = (Xu + Xl) / 2.0;
        Real64 Hnew = this->refrig->getSupHeatEnthalpy(state, Xnew, PSuctionMT, RoutineName);
        if (Hnew > this->HCompInHP) { // xnew is too high
            Xu = Xnew;
        } else { // xnew is too low
            Xl = Xnew;
        }
        if (std::abs((Hnew - this->HCompInHP) / Hnew) < ErrorTol) {
            break;
        }
    }
    this->TCompInHP = Xnew;

    //  For capacity correction of HP compressors, consider subcooler, receiver, MT loads, LT loads and LP compressors
    //  to constitute the "load".  The actual and rated conditions at the exit of the gas cooler and the inlet of the
    //  HP compressors are used for capacity correction calculations.
    DensityActualMT = this->refrig->getSupHeatDensity(state, this->TCompInHP, PSuctionMT, RoutineName);
    TotalEnthalpyChangeActualMT = this->HCompInHP - GasCooler(this->GasCoolerNum(1)).HGasCoolerOut;

    // Dispatch HP compressors
    // Before dispatching HP compressors, zero sum of compressor outputs and zero each compressor
    this->TotCompCapacityHP = 0.0;
    this->RefMassFlowCompsHP = 0.0;
    this->TotCompPowerHP = 0.0;

    for (int CompIndex = 1; CompIndex <= this->NumCompressorsHP; ++CompIndex) {
        int CompID = this->CompressorNumHP(CompIndex);
        auto &compressor = Compressor(CompID);
        compressor.Power = 0.0;
        compressor.MassFlow = 0.0;
        compressor.Capacity = 0.0;
        compressor.ElecConsumption = 0.0;
        compressor.CoolingEnergy = 0.0;
        compressor.LoadFactor = 0.0;
    }

    // Dispatch High Pressure compressors to meet load, note they were listed in compressor list in dispatch order
    for (int CompIndex = 1; CompIndex <= this->NumCompressorsHP; ++CompIndex) {
        int CompID = this->CompressorNumHP(CompIndex);
        auto &compressor = Compressor(CompID);
        // Need to use indiv compressor's rated subcool and superheat to adjust capacity to actual conditions
        // Transcritical operation requires rated superheat
        // Subcritical operation requires rated subcool and rated superheat
        switch (compressor.SubcoolRatingType) {
        case CompRatingType::Subcooling: {
            if (!GasCooler(this->GasCoolerNum(1)).TransOpFlag) { // Subcritical operation
                HCaseInRatedMT =
                    GasCooler(this->GasCoolerNum(1)).HGasCoolerOut - GasCooler(this->GasCoolerNum(1)).CpGasCoolerOut * compressor.RatedSubcool;
            } else { // Transcritical operation
                HCaseInRatedMT = GasCooler(this->GasCoolerNum(1)).HGasCoolerOut;
            } // (.NOT.GasCooler(SysNum)%TransOpFlag)
        } break;
        case CompRatingType::LiquidTemperature: {                // have rated liquid temperature stored in "RatedSubcool"
            if (!GasCooler(this->GasCoolerNum(1)).TransOpFlag) { // Subcritical operation
                HCaseInRatedMT = this->refrig->getSatEnthalpy(state, compressor.RatedSubcool, 0.0, RoutineName);
            } else { // Transcritical operation
                HCaseInRatedMT = GasCooler(this->GasCoolerNum(1)).HGasCoolerOut;
            } // (.NOT.GasCooler(SysNum)%TransOpFlag)
        } break;
        default:
            break;
        }
        switch (compressor.SuperheatRatingType) {
        case CompRatingType::Superheat: {
            HCompInRatedHP = HsatVaporforTevapneededMT + this->CpSatVapEvapMT * compressor.RatedSuperheat;
            TempInRatedHP = this->TEvapNeededMT + compressor.RatedSuperheat;
        } break;
        case CompRatingType::ReturnGasTemperature: { // have rated compressor inlet temperature stored in "RatedSuperheat"
            TempInRatedHP = compressor.RatedSuperheat;
            HCompInRatedHP = this->refrig->getSupHeatEnthalpy(state, compressor.RatedSuperheat, PSuctionMT, RoutineName);
        } break;
        default:
            break;
        }

        CaseEnthalpyChangeRatedMT = HCompInRatedHP - HCaseInRatedMT;
        DensityRatedHP = this->refrig->getSupHeatDensity(state, TempInRatedHP, PSuctionMT, RoutineName);
        //  Adjust capacity and mass flow to reflect the specific volume change due to superheating and
        //  the increase in capacity due to extra subcooling
        MassCorrectionMT = DensityActualMT / DensityRatedHP;
        CapacityCorrectionMT = MassCorrectionMT * TotalEnthalpyChangeActualMT / CaseEnthalpyChangeRatedMT;

        if (GasCooler(this->GasCoolerNum(1)).TransOpFlag) { // System is operating in transcritical region
            compressor.Power = Curve::CurveValue(state, compressor.TransElecPowerCurvePtr, TsatforPsucMT, PGCOutlet);
            compressor.Capacity = CapacityCorrectionMT * Curve::CurveValue(state, compressor.TransCapacityCurvePtr, TsatforPsucMT, HGCOutlet);
        } else { // System is operating in subcritical region
            compressor.Power = Curve::CurveValue(state, compressor.ElecPowerCurvePtr, TsatforPsucMT, TsatforPdisMT);
            compressor.Capacity = CapacityCorrectionMT * Curve::CurveValue(state, compressor.CapacityCurvePtr, TsatforPsucMT, TsatforPdisMT);
        } // (GasCooler(SysNum)%TransOpFlag)
        //  Mass flow through HP compressors is HP compressor refrigerating capacity divided by MT load, LT load and LP compressor power
        compressor.MassFlow = TotalRefMassFlow * compressor.Capacity / (NeededCapacityMT + NeededCapacityLT + this->TotCompPowerLP);
        compressor.ElecConsumption = compressor.Power * localTimeStepSec;
        compressor.CoolingEnergy = compressor.Capacity * localTimeStepSec;
        compressor.LoadFactor = 1.0;
        // calculate load factor for last compressor added
        // assumes either cycling or part load eff = full load eff for last compressor
        if ((this->TotCompCapacityHP + compressor.Capacity) >= (NeededCapacityMT + NeededCapacityLT + this->TotCompPowerLP)) {
            LFLastComp = ((NeededCapacityMT + NeededCapacityLT + this->TotCompPowerLP) - this->TotCompCapacityHP) / compressor.Capacity;
            compressor.Power *= LFLastComp;
            compressor.MassFlow *= LFLastComp;
            compressor.Capacity *= LFLastComp;
            this->TotCompCapacityHP += compressor.Capacity;
            this->RefMassFlowCompsHP += compressor.MassFlow;
            this->TotCompPowerHP += compressor.Power;
            compressor.ElecConsumption = compressor.Power * localTimeStepSec;
            compressor.CoolingEnergy = compressor.Capacity * localTimeStepSec;
            compressor.LoadFactor = LFLastComp;
            break;
        }
        this->TotCompCapacityHP += compressor.Capacity;
        this->RefMassFlowCompsHP += compressor.MassFlow;
        this->TotCompPowerHP += compressor.Power;

    } // NumCompressorsHP

    this->HCompOutHP = this->HCompInHP + this->TotCompPowerHP / this->RefMassFlowCompsHP;
    this->RefMassFlowComps = this->RefMassFlowCompsLP + this->RefMassFlowCompsHP;
    this->TotCompCapacity = this->TotCompCapacityHP + this->TotCompCapacityLP;
    this->AverageCompressorCOP = (this->TotCompCapacityHP - this->TotCompPowerLP) / (this->TotCompPowerLP + this->TotCompPowerHP);
    this->TotCompElecConsump = (this->TotCompPowerLP + this->TotCompPowerHP) * localTimeStepSec;
    this->TotCompCoolingEnergy = (this->TotCompCapacityLP + this->TotCompCapacityHP) * localTimeStepSec;
}

void RefrigSystemData::CalculateSubcoolers(EnergyPlusData &state)
{

    // SUBROUTINE INFORMATION:
    //       AUTHOR         Therese Stovall, ORNL, Assisted by Hugh Henderson
    //       DATE WRITTEN   Spring 2008
    //       MODIFIED       Brian Fricke, ORNL, March 2012, added two-stage compression
    //       RE-ENGINEERED  na

    // PURPOSE OF THIS SUBROUTINE:
    // Find the subcooler energy exchange and refrigerant states for a particular detailed
    // refrigeration system. Use the refrigerant property subroutines in FluidProperties.cc

    // METHODOLOGY EMPLOYED:
    // Use refrigerant properties and heat exchanger correlations.  NOTE:  Assumes any Mech subcooler
    // immediately follows condenser outlet (after pipe loss) and comes before any LSHX

    // REFERENCES:
    // ASHRAE 1006 Section 2: Refrigeration Accessories

    static constexpr std::string_view RoutineName = "CalculateSubcoolers";
    Real64 TLiqInActualLocal = 0.0; // Liquid T in, after condenser, before any mechanical subcooler

    auto &System = state.dataRefrigCase->System;
    auto &Condenser = state.dataRefrigCase->Condenser;
    auto &Subcooler = state.dataRefrigCase->Subcooler;

    Real64 localTimeStep = (state.dataRefrigCase->UseSysTimeStep) ? state.dataHVACGlobal->TimeStepSys : state.dataGlobal->TimeStepZone;
    Real64 localTimeStepSec = localTimeStep * Constant::rSecsInHour;

    // HCaseIn has to be recalculated as the starting point for the subcoolers here because
    //  of the multiple number of iterations through this subroutine and because Tcondense is evolving.
    if (this->NumStages == 1) { // Single-stage compression system
        this->HSatLiqCond = this->refrig->getSatEnthalpy(state, this->TCondense, 0.0, RoutineName);
        this->CpSatLiqCond = this->refrig->getSatSpecificHeat(state, this->TCondense, 0.0, RoutineName);
        this->HCaseIn = this->HSatLiqCond - this->CpSatLiqCond * Condenser(this->CondenserNum(1)).RatedSubcool;

        // Two-stage compression with flash intercooler
    } else if (this->NumStages == 2 && this->intercoolerType == IntercoolerType::Flash) {
        this->HSatLiqCond = this->refrig->getSatEnthalpy(state, this->TCondense, 0.0, RoutineName);
        this->CpSatLiqCond = this->refrig->getSatSpecificHeat(state, this->TCondense, 0.0, RoutineName);
        this->HCaseIn = this->refrig->getSatEnthalpy(state, this->TIntercooler, 0.0, RoutineName);

        // Two-stage compression with shell-and-coil intercooler
    } else if (this->NumStages == 2 && this->intercoolerType == IntercoolerType::ShellAndCoil) {
        TLiqInActualLocal = this->TCondense - Condenser(this->CondenserNum(1)).RatedSubcool -
                            this->IntercoolerEffectiveness * (this->TCondense - Condenser(this->CondenserNum(1)).RatedSubcool - this->TIntercooler);
        this->HSatLiqCond = this->refrig->getSatEnthalpy(state, this->TCondense, 0.0, RoutineName);
        this->CpSatLiqCond = this->refrig->getSatSpecificHeat(state, this->TCondense, 0.0, RoutineName);
        this->HCaseIn = this->HSatLiqCond - this->CpSatLiqCond * (this->TCondense - TLiqInActualLocal);
    } // NumStages and IntercoolerType

    for (int SubcoolerIndex = 1; SubcoolerIndex <= this->NumSubcoolers; ++SubcoolerIndex) {
        int SubcoolerID = this->SubcoolerNum(SubcoolerIndex);
        auto &cooler = Subcooler(SubcoolerID);
        // set up local variables for convenience
        Real64 DelTLiqDes = cooler.LiqSuctDesignDelT;
        Real64 TVapInDes = cooler.LiqSuctDesignTvapIn;
        Real64 TLiqInDes = cooler.LiqSuctDesignTliqIn;
        Real64 ControlTLiqOut = cooler.MechControlTliqOut;
        Real64 CpLiquid = this->CpSatLiqCond;
        Real64 CpVapor = this->CpSatVapEvap;
        if (this->NumStages == 1) { // Single-stage compression system
            TLiqInActualLocal = this->TCondense - Condenser(this->CondenserNum(1)).RatedSubcool;

            // Two-stage compression with flash intercooler
        } else if (this->NumStages == 2 && this->intercoolerType == IntercoolerType::Flash) {
            TLiqInActualLocal = this->TIntercooler;

            // Two-stage compression with shell-and-coil intercooler
        } else if (this->NumStages == 2 && this->intercoolerType == IntercoolerType::ShellAndCoil) {
            TLiqInActualLocal =
                this->TCondense - Condenser(this->CondenserNum(1)).RatedSubcool -
                this->IntercoolerEffectiveness * (this->TCondense - Condenser(this->CondenserNum(1)).RatedSubcool - this->TIntercooler);
        } // NumStages and IntercoolerType

        switch (cooler.subcoolerType) {
            // Mechanical subcoolers required to come first in order to take advantage of delT
            //  from lshx. taken care of because subcooler ID assigned in that order in input.
        case SubcoolerType::Mechanical: {
            Real64 mechSCLoad = this->RefMassFlowtoLoads * CpLiquid * (TLiqInActualLocal - ControlTLiqOut);
            this->HCaseIn -= CpLiquid * (TLiqInActualLocal - ControlTLiqOut);
            // refrigeration benefit to System(sysnum)
            // refrigeration load must be assigned properly according to input
            int SysProvideID = cooler.MechSourceSysID;
            System(SysProvideID).MechSCLoad(SubcoolerID) = mechSCLoad;
            cooler.MechSCTransLoad = mechSCLoad;
            cooler.MechSCTransEnergy = mechSCLoad * localTimeStepSec;
            // Reset inlet temperature for any LSHX that follows this mech subcooler
            TLiqInActualLocal = ControlTLiqOut;
            this->TCompIn = this->TEvapNeeded + CaseSuperheat;
        } break;
        case SubcoolerType::LiquidSuction: {
            Real64 LSHXeffectiveness = DelTLiqDes / (TLiqInDes - TVapInDes);
            Real64 TVapInActual = this->TEvapNeeded + CaseSuperheat;
            Real64 DelTempActual = LSHXeffectiveness * (TLiqInActualLocal - TVapInActual);
            TLiqInActualLocal -= DelTempActual;
            Real64 SubcoolLoad = this->RefMassFlowtoLoads * CpLiquid * DelTempActual;
            Real64 SubcoolerSupHeat = SubcoolLoad / CpVapor / this->RefMassFlowComps;
            this->TCompIn = TVapInActual + SubcoolerSupHeat;
            this->HCaseIn -= SubcoolLoad / this->RefMassFlowtoLoads;
            this->LSHXTrans = SubcoolLoad;
            this->LSHXTransEnergy = SubcoolLoad * localTimeStepSec;
        } break;
        default:
            break;
        }

        this->TLiqInActual = TLiqInActualLocal;
    }
}

void GetRefrigeratedRackIndex(EnergyPlusData &state,
                              std::string const &Name,
                              int &IndexPtr,
                              DataHeatBalance::RefrigSystemType const SysType,
                              bool &ErrorsFound,
                              std::string_view const ThisObjectType,
                              bool const SuppressWarning)
{

    // SUBROUTINE INFORMATION:
    //       AUTHOR         Richard Raustad
    //       DATE WRITTEN   June 2007
    //       MODIFIED       Therese Stovall May 2008
    //       RE-ENGINEERED  na
    // PURPOSE OF THIS SUBROUTINE:
    // This subroutine sets an index for a given refrigerated rack or refrigeration condenser
    //  -- issues error message if the rack or condenser is not found.

    auto &RefrigRack = state.dataRefrigCase->RefrigRack;
    auto &Condenser = state.dataRefrigCase->Condenser;

    CheckRefrigerationInput(state);

    switch (SysType) {
    case DataHeatBalance::RefrigSystemType::Rack: {
        IndexPtr = Util::FindItemInList(Name, RefrigRack);
        if (IndexPtr == 0) {
            if (SuppressWarning) {
                //     No warning printed if only searching for the existence of a refrigerated rack
            } else {
                if (!ThisObjectType.empty()) {
                    ShowSevereError(state, fmt::format("{}, GetRefrigeratedRackIndex: Rack not found={}", ThisObjectType, Name));
                } else {
                    if (!ThisObjectType.empty()) {
                        ShowSevereError(state, fmt::format("{}, GetRefrigeratedRackIndex: Rack not found={}", ThisObjectType, Name));
                    } else {
                        ShowSevereError(state, format("GetRefrigeratedRackIndex: Rack not found={}", Name));
                    }
                }
            }
            ErrorsFound = true;
        }
    } break;
    case DataHeatBalance::RefrigSystemType::Detailed: {
        IndexPtr = Util::FindItemInList(Name, Condenser);
        if (IndexPtr == 0) {
            if (SuppressWarning) {
                //     No warning printed if only searching for the existence of a refrigeration Condenser
            } else {
                if (!ThisObjectType.empty()) {
                    ShowSevereError(state, fmt::format("{}, GetRefrigeratedRackIndex: Condenser not found={}", ThisObjectType, Name));
                } else {
                    ShowSevereError(state, format("GetRefrigeratedRackIndex: Condenser not found={}", Name));
                }
            }
        }
        ErrorsFound = true;
    } break;
    default:
        break;
    }
}

void ReportRefrigerationComponents(EnergyPlusData &state)
{

    // SUBROUTINE INFORMATION:
    //       AUTHOR         Richard Raustad, FSEC
    //       DATE WRITTEN   October 2004
    //       MODIFIED       Shirey, FSEC Dec 2004; Lawrie, Mar 2008 - Node names, not numbers.
    //       MODIFIED       Stovall - 2008 to 2010, new refrig variables and move orphan reporting to input.
    //       MODIFIED       Fricke, ORNL, Fall 2011, added transcritical CO2 refrigeration system variables
    //       RE-ENGINEERED  na

    // PURPOSE OF THIS SUBROUTINE:
    // To report information from the input deck for refrigerated cases and racks to the eio and err file.

    std::string ChrOut;
    std::string ChrOut2;

    auto &RefrigCase = state.dataRefrigCase->RefrigCase;
    auto &RefrigRack = state.dataRefrigCase->RefrigRack;
    auto &System = state.dataRefrigCase->System;
    auto &TransSystem = state.dataRefrigCase->TransSystem;
    auto &Condenser = state.dataRefrigCase->Condenser;
    auto &Compressor = state.dataRefrigCase->Compressor;
    auto &GasCooler = state.dataRefrigCase->GasCooler;
    auto &Subcooler = state.dataRefrigCase->Subcooler;
    auto &Secondary = state.dataRefrigCase->Secondary;
    auto &WalkIn = state.dataRefrigCase->WalkIn;
    auto &WarehouseCoil = state.dataRefrigCase->WarehouseCoil;
    auto &AirChillerSet = state.dataRefrigCase->AirChillerSet;

    static constexpr std::string_view Format_104(
        "! <Refrigeration Compressor Rack>,Compressor Rack Name, # Refrigerated Cases Connected,# WalkIn Coolers "
        "Connected, Heat Rejection Location, Condenser Type, COP");
    static constexpr std::string_view Format_105(
        "!  <Refrigeration Case>,Refrigeration Case Number, Refrigeration Case Name,Zone Name,Zone Node #,Zone "
        "Node Name,Capacity (W/m),LHR,Temperature (C),Length (m),Fan (W/m),Installed Lighting (W/m),Anti-Sweat "
        "(W/m),Defrost (W/m)");
    static constexpr std::string_view Format_108("!  <Refrigeration Compressor>,Compressor Number,Compressor Name,Nominal Capacity (W)");
    static constexpr std::string_view Format_109("! <#Refrigeration Compressor Racks>,Number of Refrigeration Compressor Racks");
    static constexpr std::string_view Format_117("! <#Detailed Refrigeration Systems>,Number of Detailed Refrigeration Systems");
    static constexpr std::string_view Format_118(
        "! <Detailed Refrigeration System>,Refrigeration System Name,Refrigerant Used, # Refrigerated Cases "
        "Connected, # WalkInCoolers Connected, #Air Chillers Connected, # Secondary Loops Served, # Cascade Condensers "
        "Served, # Mechanical Subcoolers Served, # Compressors Connected, # Compression Stages, Intercooler Type, "
        "Intercooler Effectiveness, # Subcoolers Connected, Minimum Condensing Temperature (C)");
    static constexpr std::string_view Format_119(
        "!  <Refrigeration Walk In Cooler>, Walk In Number, Walk In Name,Capacity (W),Temperature (C),Coil Fan "
        "(W), Circulating Fan (W), Lighting (W),Heaters (W),Defrost (W), # Zones");
    static constexpr std::string_view Format_120(
        "! <#Detailed Transcritical Refrigeration Systems>,Number of Detailed Transcritical Refrigeration Systems");
    static constexpr std::string_view Format_121(
        "! <Detailed Transcritical Refrigeration System>,Transcritical Refrigeration System Name,Refrigerant Used, # "
        "Medium Temperature Refrigerated Cases Connected, # Low Temperature Refrigerated Cases Connected, # Medium "
        "Temperature WalkInCoolers Connected, # Low Temperature WalkInCoolers Connected, # High Pressure Compressors "
        "Connected, # Low Pressure Compressors Connected, Minimum Condensing Temperature (C)");
    static constexpr std::string_view Format_123("!  <Secondary Load>, Secondary System Served Name, Secondary Number");
    static constexpr std::string_view Format_126(
        "!  <Refrigeration Mechanical Subcooler>, Subcooler Number, Subcooler Name, Name of System Providing "
        "Cooling, Design Outlet Temperature (C)");
    static constexpr std::string_view Format_127("!  <Refrigeration Liquid Suction Subcooler>, Subcooler Number, Subcooler Name, Design Subcooling "
                                                 "(DeltaC),Design liquid inlet temperature (C), Design vapor inlet temperature (C)");
    static constexpr std::string_view Format_128("!  <Cascade Load>, System Name Connected, Condenser Number, Condenser Name");
    static constexpr std::string_view Format_129(
        "!  <Refrigeration Condenser:Air-Cooled>,Condenser Number,Condenser Name,Rated Condensing Temperature "
        "(C),Rated Capacity (W), Rated Fan Power (W)");
    static constexpr std::string_view Format_130(
        "!  <Refrigeration Condenser:Water-Cooled>,Condenser Number,Condenser Name,Rated Condensing Temperature "
        "(C),Rated Capacity (W), Rated Water Inlet Temperature (C), Rated Water Flow Rate (m3/s)");
    static constexpr std::string_view Format_131(
        "!  <Refrigeration Condenser:Evaporative-Cooled>,Condenser Number,Condenser Name,Rated Capacity (W), Rated Fan Power (W)");
    static constexpr std::string_view Format_132(
        "!  <Refrigeration Condenser:Cascade>, Condenser Number, Condenser Name, Condensing Temperature Control "
        "Type, Rated Condensing Temperature (C), Capacity (W), Approach Temperature Difference (DeltaC)");
    static constexpr std::string_view Format_133(
        "! <Secondary Refrigeration System: Fluid Always Liquid>, Secondary Number, Secondary Name, # Refrigerated "
        "Cases Connected, # WalkIn Coolers Connected, Fluid Name, Capacity (W),Evap Temperature in Secondary "
        "Evaporator (C), Approach Temperature Difference (DeltaC), Temperature Range (DeltaC), TotalPumpPower (W)");
    static constexpr std::string_view Format_134(
        "!      <Walk-In Surfaces Facing Zone>, ZoneName, Wall/Ceiling Area (m2), UValue (W/m2-C), AreaStockDoors "
        "(m2), HeightStockDoors, UValueStockDoors (W/m2-C), AreaGlassDoors (m2), HeightGlassDoors (m),  "
        "UValueGlassDoors (W/m2-C)");
    static constexpr std::string_view Format_141("!  <Mechanical Subcooler Load>, Subcooler Number, Subcooler Name");
    static constexpr std::string_view Format_142("! <#Secondary Refrigeration Systems>,Number of Secondary Refrigeration Systems");
    static constexpr std::string_view Format_146(
        "! <Secondary Refrigeration System: Liquid Overfeed>, Secondary Number, Secondary Name, # Refrigerated Cases "
        "Connected, # WalkIn Coolers Connected, #Air Coils Connected Fluid Name, Capacity (W),Evap Temperature in "
        "Secondary Evaporator (C), Approach Temperature Difference (DeltaC), Circulating Rate, TotalPumpPower (W)");
    static constexpr std::string_view Format_148("! <#ZoneHVAC/Refrigeration Air Chiller Sets>,Number of ZoneHVAC/Refrigeration Air Chiller Sets");
    static constexpr std::string_view Format_149(
        "! <ZoneHVAC/Refrigeration Air Chiller Set>,Chiller Set Name, # Air Chillers Connected, Zone Location");
    static constexpr std::string_view Format_151(
        "!  <Refrigeration Air Chiller>,Refrigeration Chiller Number, Refrigeration Chiller Name,Zone Name,Zone "
        "Node #,Zone Node Name,Sensible Capacity (W/C),Sensible Capacity (W),Evaporating Temperature (C),DT1 (C),Fan "
        "Power (W),Heater (W),Defrost (W), Air Flow Rate (m3/s)");
    static constexpr std::string_view Format_152("!  <Air Chiller Load>, Air Chiller Name, Air Chiller Number, Zone Name");
    static constexpr std::string_view Format_160(
        "!  <Refrigeration GasCooler:Air-Cooled>,Gas Cooler Number, Gas Cooler Name, Rated Outlet Pressure "
        "(Pa),Rated Outlet Temperature (C), Rated Approach Temperature (C), Rated Capacity (W), Rated Fan Power (W)");

    // write all headers applicable to this simulation
    if (state.dataRefrigCase->NumRefrigeratedRacks > 0) {
        print(state.files.eio, "{}\n", Format_109); // Intro to refrigeration case racks
        print(state.files.eio, "{}\n", Format_104); // Refrigeration Rack header
    } //(NumRefrigeratedRacks > 0)
    if (state.dataRefrigCase->NumRefrigSystems > 0) {
        print(state.files.eio, "{}\n", Format_117); // Intro to detailed systems
        print(state.files.eio, "{}\n", Format_118); // Detailed system header
        print(state.files.eio, "{}\n", Format_108); // Compressor header (Always have compressor if have detailed system)
    } //(NumRefrigSystems > 0)
    if (state.dataRefrigCase->NumSimulationSecondarySystems > 0) {
        print(state.files.eio, "{}\n", Format_142); // Intro to Secondary systems
        int CountSecPhase = 0;
        int CountSecBrine = 0;
        for (int SecondaryID = 1; SecondaryID <= state.dataRefrigCase->NumSimulationSecondarySystems; ++SecondaryID) {
            if ((Secondary(SecondaryID).FluidType == SecFluidType::AlwaysLiquid) && (CountSecBrine == 0)) {
                print(state.files.eio, "{}\n", Format_133); // Secondary system header for brine type systems
                ++CountSecBrine;
            }
            if ((Secondary(SecondaryID).FluidType == SecFluidType::PhaseChange) && (CountSecPhase == 0)) {
                print(state.files.eio, "{}\n", Format_146); // Secondary system header for liquid overfeed/phase change systems
                ++CountSecPhase;
            }
        }
        print(state.files.eio, "{}\n", Format_123); //  Secondary system load header
    } //(NumSimulationSecondarySystems > 0)
    if (state.dataRefrigCase->NumRefrigChillerSets > 0) {
        print(state.files.eio, "{}\n", Format_148); // Intro to Chiller set
        print(state.files.eio, "{}\n", Format_149); // Chiller set header
        print(state.files.eio, "{}\n", Format_151); // Intro to Air Chiller
        print(state.files.eio, "{}\n", Format_152); // Air chiller header
    } //(NumRefrigSystems > 0)
    if (state.dataRefrigCase->NumSimulationCases > 0) {
        print(state.files.eio, "{}\n", Format_105); //  Case header
    } //(NumSimulationCases > 0)
    if (state.dataRefrigCase->NumSimulationWalkIns > 0) {
        print(state.files.eio, "{}\n", Format_119); //  Walk-in header
        print(state.files.eio, "{}\n", Format_134); //  Walk-in zone-specific header
    } //(NumSimulationWalkIns > 0)
    if (state.dataRefrigCase->NumSimulationCondAir > 0) {
        print(state.files.eio, "{}\n", Format_129); //  Condenser, Air-Cooled header
    } //(NumSimulationCondAir > 0)
    if (state.dataRefrigCase->NumSimulationCondEvap > 0) {
        print(state.files.eio, "{}\n", Format_131); //  Condenser, Evaporative-Cooled header
    } //(NumSimulationCondEvap > 0)
    if (state.dataRefrigCase->NumSimulationCondWater > 0) {
        print(state.files.eio, "{}\n", Format_130); //  Condenser, Water-Cooled header
    } //(NumSimulationCondWater > 0)
    if (state.dataRefrigCase->NumSimulationCascadeCondensers > 0) {
        print(state.files.eio, "{}\n", Format_132); //  Condenser, Cascade header
        print(state.files.eio, "{}\n", Format_128); //  Cascade Load header
    } //(NumSimulationCascadeCondensers > 0)
    if (state.dataRefrigCase->NumSimulationMechSubcoolers > 0) {
        print(state.files.eio, "{}\n", Format_141); //  Mech subcooler loads served header
        print(state.files.eio, "{}\n", Format_126); //  Mechanical Subcooler header
    } //(NumSimulationMechSubcoolers > 0)
    if ((state.dataRefrigCase->NumSimulationSubcoolers - state.dataRefrigCase->NumSimulationMechSubcoolers) > 0) {
        print(state.files.eio, "{}\n", Format_127); //  LSHX Subcooler header
    } //((NumSimulationSubcoolers - NumSimulationMechSubcoolers) > 0)

    if (state.dataRefrigCase->NumTransRefrigSystems > 0) {
        print(state.files.eio, "{}\n", Format_120); // Intro to detailed transcritical refrigeration system
        print(state.files.eio, "{}\n", Format_121); // Detailed system header
        if (state.dataRefrigCase->NumSimulationCases > 0) {
            print(state.files.eio, "{}\n", Format_105); //  Case header
        } //(NumSimulationCases > 0)
        if (state.dataRefrigCase->NumSimulationWalkIns > 0) {
            print(state.files.eio, "{}\n", Format_119); //  Walk-in header
            print(state.files.eio, "{}\n", Format_134); //  Walk-in zone-specific header
        } //(NumSimulationWalkIns > 0)
        print(state.files.eio, "{}\n", Format_108); // Compressor header (Always have compressor if have detailed system)
        if (state.dataRefrigCase->NumSimulationGasCooler > 0) {
            print(state.files.eio, "{}\n", Format_160); //  Gas Cooler, Air-Cooled header
        } //(NumSimulationGasCooler > 0)
    } //(NumTransRefrigSystems > 0)

    if (state.dataRefrigCase->NumRefrigeratedRacks > 0) {
        print(state.files.eio, "#Refrigeration Compressor Racks, {}\n", state.dataRefrigCase->NumRefrigeratedRacks);
        for (int RackNum = 1; RackNum <= state.dataRefrigCase->NumRefrigeratedRacks; ++RackNum) {
            if (RefrigRack(RackNum).HeatRejectionLocation == HeatRejLocation::Outdoors) {
                ChrOut = "Outdoors";
            } else {
                ChrOut = "Zone";
            }
            switch (RefrigRack(RackNum).CondenserType) {
            case DataHeatBalance::RefrigCondenserType::Air: {
                ChrOut2 = "Air-Cooled";
            } break;
            case DataHeatBalance::RefrigCondenserType::Evap: {
                ChrOut2 = "Evap-Cooled";
            } break;
            case DataHeatBalance::RefrigCondenserType::Water: {
                ChrOut2 = "Water-Cooled";
            } break;
            default:
                break;
            }
            print(state.files.eio,
                  " Refrigeration Compressor Rack,{},{},{},{},{},{:.3R}\n",
                  RefrigRack(RackNum).Name,
                  RefrigRack(RackNum).NumCases,
                  RefrigRack(RackNum).NumWalkIns,
                  ChrOut,
                  ChrOut2,
                  RefrigRack(RackNum).RatedCOP);
            for (int CaseNum = 1; CaseNum <= RefrigRack(RackNum).NumCases; ++CaseNum) {
                int CaseID = RefrigRack(RackNum).CaseNum(CaseNum);
                if (RefrigCase(CaseID).ZoneNodeNum > 0) {
                    print(state.files.eio,
                          "   Refrigeration Case,{},{},{},{},{},{:.1R},{:.2R},{:.1R},{:.1R},{:.1R},{:.1R},{:.1R},{:.1R}\n",
                          CaseID,
                          RefrigCase(CaseID).Name,
                          RefrigCase(CaseID).ZoneName,
                          RefrigCase(CaseID).ZoneNodeNum,
                          state.dataLoopNodes->NodeID(RefrigCase(CaseID).ZoneNodeNum),
                          RefrigCase(CaseID).RateTotCapPerLength,
                          RefrigCase(CaseID).RatedLHR,
                          RefrigCase(CaseID).Temperature,
                          RefrigCase(CaseID).Length,
                          RefrigCase(CaseID).OperatingFanPower,
                          RefrigCase(CaseID).LightingPower,
                          RefrigCase(CaseID).AntiSweatPower,
                          RefrigCase(CaseID).DefrostPower); // Installed lighting power, may not be rated power
                }
            } // numcases

            for (int WalkInNum = 1; WalkInNum <= RefrigRack(RackNum).NumWalkIns; ++WalkInNum) {
                int WalkInID = RefrigRack(RackNum).WalkInNum(WalkInNum);
                print(state.files.eio,
                      "   Refrigeration Walk In Cooler,  {},{},{:.1R},{:.1R},{:.1R},{:.1R},{:.1R},{:.1R},{:.1R},{:.1R},{}\n",
                      WalkInID,
                      WalkIn(WalkInID).Name,
                      WalkIn(WalkInID).DesignRatedCap,
                      WalkIn(WalkInID).Temperature,
                      WalkIn(WalkInID).CoilFanPower,
                      WalkIn(WalkInID).CircFanPower,
                      WalkIn(WalkInID).ElecFanPower,
                      WalkIn(WalkInID).DesignLighting,
                      WalkIn(WalkInID).HeaterPower,
                      WalkIn(WalkInID).DefrostCapacity,
                      WalkIn(WalkInID).NumZones);
                for (int ZoneID = 1; ZoneID <= WalkIn(WalkInID).NumZones; ++ZoneID) {
                    print(state.files.eio,
                          "      Walk-In Surfaces Facing Zone, {},{:.1R},{:.4R},{:.2R},{:.2R},{:.4R},{:.2R},{:.2R},{:.4R}\n",
                          WalkIn(WalkInID).ZoneName(ZoneID),
                          WalkIn(WalkInID).SurfaceArea(ZoneID),
                          WalkIn(WalkInID).UValue(ZoneID),
                          WalkIn(WalkInID).AreaStockDr(ZoneID),
                          WalkIn(WalkInID).HeightStockDr(ZoneID),
                          WalkIn(WalkInID).UValueStockDr(ZoneID),
                          WalkIn(WalkInID).AreaGlassDr(ZoneID),
                          WalkIn(WalkInID).HeightGlassDr(ZoneID),
                          WalkIn(WalkInID).UValueGlassDr(ZoneID));
                } // zones for walk ins on rack
            } // walk ins on rack

            for (int CoilNum = 1; CoilNum <= RefrigRack(RackNum).NumCoils; ++CoilNum) {
                int CoilID = RefrigRack(RackNum).CoilNum(CoilNum);
                print(state.files.eio, "   Air Chiller Load,{},{},{}\n", WarehouseCoil(CoilID).Name, CoilID, WarehouseCoil(CoilID).ZoneName);
            } // numairchillers
        } // numracks
    } //(NumRefrigeratedRacks > 0)

    if (state.dataRefrigCase->NumRefrigSystems > 0) {
        print(state.files.eio, "#Detailed Refrigeration Systems,{}\n", state.dataRefrigCase->NumRefrigSystems);
        for (int SystemNum = 1; SystemNum <= state.dataRefrigCase->NumRefrigSystems; ++SystemNum) {
            print(state.files.eio,
                  " Detailed Refrigeration System,{},{},{},{},{},{},{},{},{},{},{},{:.2R},{},{:.1R}\n",
                  System(SystemNum).Name,
                  System(SystemNum).RefrigerantName,
                  System(SystemNum).NumCases,
                  System(SystemNum).NumWalkIns,
                  System(SystemNum).NumCoils,
                  System(SystemNum).NumSecondarys,
                  System(SystemNum).NumCascadeLoads,
                  System(SystemNum).NumMechSCServed,
                  System(SystemNum).NumCompressors + System(SystemNum).NumHiStageCompressors,
                  System(SystemNum).NumStages,
                  System(SystemNum).intercoolerType,
                  System(SystemNum).IntercoolerEffectiveness,
                  System(SystemNum).NumSubcoolers,
                  System(SystemNum).TCondenseMin);

            for (int CaseNum = 1; CaseNum <= System(SystemNum).NumCases; ++CaseNum) {
                int CaseID = System(SystemNum).CaseNum(CaseNum);
                if (RefrigCase(CaseID).ZoneNodeNum > 0) {
                    print(state.files.eio,
                          "   Refrigeration Case,{},{},{},{},{},{:.1R},{:.2R},{:.1R},{:.1R},{:.1R},{:.1R},{:.1R},{:.1R}\n",
                          CaseID,
                          RefrigCase(CaseID).Name,
                          RefrigCase(CaseID).ZoneName,
                          RefrigCase(CaseID).ZoneNodeNum,
                          state.dataLoopNodes->NodeID(RefrigCase(CaseID).ZoneNodeNum),
                          RefrigCase(CaseID).RateTotCapPerLength,
                          RefrigCase(CaseID).RatedLHR,
                          RefrigCase(CaseID).Temperature,
                          RefrigCase(CaseID).Length,
                          RefrigCase(CaseID).OperatingFanPower,
                          RefrigCase(CaseID).LightingPower,
                          RefrigCase(CaseID).AntiSweatPower,
                          RefrigCase(CaseID).DefrostPower);
                }
            } // NumCases on system
            for (int WalkInNum = 1; WalkInNum <= System(SystemNum).NumWalkIns; ++WalkInNum) {
                int WalkInID = System(SystemNum).WalkInNum(WalkInNum);
                print(state.files.eio,
                      "   Refrigeration Walk In Cooler,{},{},{:.1R},{:.1R},{:.1R},{:.1R},{:.1R},{:.1R},{:.1R},{}\n",
                      WalkInID,
                      WalkIn(WalkInID).Name,
                      WalkIn(WalkInID).DesignRatedCap,
                      WalkIn(WalkInID).Temperature,
                      WalkIn(WalkInID).CoilFanPower,
                      WalkIn(WalkInID).CircFanPower,
                      WalkIn(WalkInID).DesignLighting,
                      WalkIn(WalkInID).HeaterPower,
                      WalkIn(WalkInID).DefrostCapacity,
                      WalkIn(WalkInID).NumZones);
                for (int ZoneID = 1; ZoneID <= WalkIn(WalkInID).NumZones; ++ZoneID) {
                    print(state.files.eio,
                          "      Walk-In Surfaces Facing Zone, {},{:.1R},{:.4R},{:.2R},{:.2R},{:.4R},{:.2R},{:.2R},{:.4R}\n",
                          WalkIn(WalkInID).ZoneName(ZoneID),
                          WalkIn(WalkInID).SurfaceArea(ZoneID),
                          WalkIn(WalkInID).UValue(ZoneID),
                          WalkIn(WalkInID).AreaStockDr(ZoneID),
                          WalkIn(WalkInID).HeightStockDr(ZoneID),
                          WalkIn(WalkInID).UValueStockDr(ZoneID),
                          WalkIn(WalkInID).AreaGlassDr(ZoneID),
                          WalkIn(WalkInID).HeightGlassDr(ZoneID),
                          WalkIn(WalkInID).UValueGlassDr(ZoneID));
                } // Num zones for each walk in on system
            } // NumWalkIns on system

            for (int CoilNum = 1; CoilNum <= System(SystemNum).NumCoils; ++CoilNum) {
                int CoilID = System(SystemNum).CoilNum(CoilNum);
                print(state.files.eio, "   Air Chiller Load,{},{},{}\n", WarehouseCoil(CoilID).Name, CoilID, WarehouseCoil(CoilID).ZoneName);
            } // numairchillers

            for (int CascadeLoadNum = 1; CascadeLoadNum <= System(SystemNum).NumCascadeLoads; ++CascadeLoadNum) {
                int CascadeLoadID = System(SystemNum).CascadeLoadNum(CascadeLoadNum);
                print(state.files.eio,
                      "   Cascade Load,{},{},{}\n",
                      System(Condenser(CascadeLoadID).CascadeSysID).Name,
                      CascadeLoadID,
                      Condenser(CascadeLoadID).Name);
            } // cascade load on detailed system

            for (int SecondaryNum = 1; SecondaryNum <= System(SystemNum).NumSecondarys; ++SecondaryNum) {
                int SecondaryID = System(SystemNum).SecondaryNum(SecondaryNum);
                print(state.files.eio, "   Secondary Load,{},{}\n", Secondary(SecondaryID).Name, SecondaryID);
            } // secondary load on detailed system

            for (int SubcoolerNum = 1; SubcoolerNum <= state.dataRefrigCase->NumSimulationSubcoolers; ++SubcoolerNum) {
                if (Subcooler(SubcoolerNum).MechSourceSysID != SystemNum) {
                    continue;
                }
                print(state.files.eio, "   Mechanical Subcooler Load, {},{}\n", SubcoolerNum, Subcooler(SubcoolerNum).Name);
            } // Num sim subcoolers, looking only for NumSMech Subcoolers served by this system

            if (System(SystemNum).NumStages == 1) { // Single-stage compression system
                for (int CompressorNum = 1; CompressorNum <= System(SystemNum).NumCompressors; ++CompressorNum) {
                    int CompID = System(SystemNum).CompressorNum(CompressorNum);
                    print(state.files.eio, "   Refrigeration Compressor,{},{},{:.0R}\n", CompID, Compressor(CompID).Name, Compressor(CompID).NomCap);
                } // NumCompressors
            } else if (System(SystemNum).NumStages == 2) { // Two-stage compression system
                // Low-stage compressors
                for (int CompressorNum = 1; CompressorNum <= System(SystemNum).NumCompressors; ++CompressorNum) {
                    int CompID = System(SystemNum).CompressorNum(CompressorNum);
                    print(state.files.eio,
                          "   Refrigeration Low-Stage Compressor,{},{},{:.0R}\n",
                          CompID,
                          Compressor(CompID).Name,
                          Compressor(CompID).NomCap);
                } // NumCompressors
                // High-stage compressors
                for (int CompressorNum = 1; CompressorNum <= System(SystemNum).NumHiStageCompressors; ++CompressorNum) {
                    int CompID = System(SystemNum).HiStageCompressorNum(CompressorNum);
                    print(state.files.eio,
                          "   Refrigeration High-Stage Compressor,{},{},{:.0R}\n",
                          CompID,
                          Compressor(CompID).Name,
                          Compressor(CompID).NomCap);
                } // NumHiStageCompressors
            } // NumStages

            int CondID = System(SystemNum).CondenserNum(1);
            switch (Condenser(CondID).CondenserType) {
            case DataHeatBalance::RefrigCondenserType::Air: {
                print(state.files.eio,
                      "   Refrigeration Condenser:Air-Cooled,{},{},{:.1R},{:.1R},{:.1R}\n",
                      CondID,
                      Condenser(CondID).Name,
                      Condenser(CondID).RatedTCondense,
                      Condenser(CondID).RatedCapacity,
                      Condenser(CondID).RatedFanPower);
            } break;
            case DataHeatBalance::RefrigCondenserType::Evap: {
                print(state.files.eio,
                      "   Refrigeration Condenser:Evaporative-Cooled,{},{},{:.1R},{:.1R}\n",
                      CondID,
                      Condenser(CondID).Name,
                      Condenser(CondID).RatedCapacity,
                      Condenser(CondID).RatedFanPower);
            } break;
            case DataHeatBalance::RefrigCondenserType::Water: {
                print(state.files.eio,
                      "   Refrigeration Condenser:Water-Cooled,{},{},{:.1R},{:.1R},{:.1R},{:.1R}\n",
                      CondID,
                      Condenser(CondID).Name,
                      Condenser(CondID).RatedTCondense,
                      Condenser(CondID).RatedCapacity,
                      Condenser(CondID).InletTemp,
                      Condenser(CondID).DesVolFlowRate);
            } break;
            case DataHeatBalance::RefrigCondenserType::Cascade: {

                switch (Condenser(CondID).CascadeTempControl) {
                case CascadeCndsrTempCtrlType::TempSet: {
                    ChrOut = "Fixed";
                } break;
                case CascadeCndsrTempCtrlType::TempFloat: {
                    ChrOut = "Floating";
                } break;
                default:
                    break;
                } // cascade temperature control
                print(state.files.eio,
                      "   Refrigeration Condenser:Cascade,{},{},{},{:.1R},{:.1R},{:.1R}\n",
                      CondID,
                      Condenser(CondID).Name,
                      ChrOut,
                      Condenser(CondID).RatedTCondense,
                      Condenser(CondID).RatedCapacity,
                      Condenser(CondID).RatedApproachT);
            } break;
            default:
                break;
            } // condenser type

            for (int SubcoolerNum = 1; SubcoolerNum <= System(SystemNum).NumSubcoolers; ++SubcoolerNum) {
                int SubcoolerID = System(SystemNum).SubcoolerNum(SubcoolerNum);
                switch (Subcooler(SubcoolerID).subcoolerType) {
                case SubcoolerType::LiquidSuction: {
                    print(state.files.eio,
                          "   Refrigeration Liquid Suction Subcooler,{},{},{:.1R},{:.1R},{:.1R}\n",
                          SubcoolerID,
                          Subcooler(SubcoolerID).Name,
                          Subcooler(SubcoolerID).LiqSuctDesignDelT,
                          Subcooler(SubcoolerID).LiqSuctDesignTliqIn,
                          Subcooler(SubcoolerID).LiqSuctDesignTvapIn);
                } break;
                case SubcoolerType::Mechanical: {
                    print(state.files.eio,
                          "   Refrigeration Mechanical Subcooler,{},{},{},{:.1R}\n",
                          SubcoolerID,
                          Subcooler(SubcoolerID).Name,
                          Subcooler(SubcoolerID).MechSourceSys,
                          Subcooler(SubcoolerID).MechControlTliqOut);
                } break;
                default:
                    break;
                }
            } // NumSubcoolers

        } // NumRefrigSystems
    } //(NumRefrigSystems > 0)

    if (state.dataRefrigCase->NumTransRefrigSystems > 0) {
        print(state.files.eio, "#Detailed Transcritical Refrigeration Systems,{}\n", state.dataRefrigCase->NumTransRefrigSystems);
        for (int TransSystemNum = 1; TransSystemNum <= state.dataRefrigCase->NumTransRefrigSystems; ++TransSystemNum) {
            print(state.files.eio,
                  " Detailed Transcritical Refrigeration System,{},{},{},{},{},{},{},{},{:.1R}\n",
                  TransSystem(TransSystemNum).Name,
                  TransSystem(TransSystemNum).RefrigerantName,
                  TransSystem(TransSystemNum).NumCasesMT,
                  TransSystem(TransSystemNum).NumCasesLT,
                  TransSystem(TransSystemNum).NumWalkInsMT,
                  TransSystem(TransSystemNum).NumWalkInsLT,
                  TransSystem(TransSystemNum).NumCompressorsHP,
                  TransSystem(TransSystemNum).NumCompressorsLP,
                  GasCooler(TransSystem(TransSystemNum).GasCoolerNum(1)).MinCondTemp);

            for (int CaseNum = 1; CaseNum <= TransSystem(TransSystemNum).NumCasesMT; ++CaseNum) {
                int CaseID = TransSystem(TransSystemNum).CaseNumMT(CaseNum);
                if (RefrigCase(CaseID).ZoneNodeNum > 0) {
                    print(state.files.eio,
                          "   Medium Temperature Refrigeration Case,{},{},{},{},{},{:.1R},{:.2R},{:.1R},{:.1R},{:.1R},{:.1R},{:.1R},{:.1R}\n",
                          CaseID,
                          RefrigCase(CaseID).Name,
                          RefrigCase(CaseID).ZoneName,
                          RefrigCase(CaseID).ZoneNodeNum,
                          state.dataLoopNodes->NodeID(RefrigCase(CaseID).ZoneNodeNum),
                          RefrigCase(CaseID).RateTotCapPerLength,
                          RefrigCase(CaseID).RatedLHR,
                          RefrigCase(CaseID).Temperature,
                          RefrigCase(CaseID).Length,
                          RefrigCase(CaseID).OperatingFanPower,
                          RefrigCase(CaseID).LightingPower,
                          RefrigCase(CaseID).AntiSweatPower,
                          RefrigCase(CaseID).DefrostPower);
                }
            } // NumCasesMT on system
            for (int CaseNum = 1; CaseNum <= TransSystem(TransSystemNum).NumCasesLT; ++CaseNum) {
                int CaseID = TransSystem(TransSystemNum).CaseNumLT(CaseNum);
                if (RefrigCase(CaseID).ZoneNodeNum > 0) {
                    print(state.files.eio,
                          "   Low Temperature Refrigeration Case,{},{},{},{},{},{:.1R},{:.2R},{:.1R},{:.1R},{:.1R},{:.1R},{:.1R},{:.1R}\n",
                          CaseID,
                          RefrigCase(CaseID).Name,
                          RefrigCase(CaseID).ZoneName,
                          RefrigCase(CaseID).ZoneNodeNum,
                          state.dataLoopNodes->NodeID(RefrigCase(CaseID).ZoneNodeNum),
                          RefrigCase(CaseID).RateTotCapPerLength,
                          RefrigCase(CaseID).RatedLHR,
                          RefrigCase(CaseID).Temperature,
                          RefrigCase(CaseID).Length,
                          RefrigCase(CaseID).OperatingFanPower,
                          RefrigCase(CaseID).LightingPower,
                          RefrigCase(CaseID).AntiSweatPower,
                          RefrigCase(CaseID).DefrostPower);
                }
            } // NumCasesLT on system
            for (int WalkInNum = 1; WalkInNum <= TransSystem(TransSystemNum).NumWalkInsMT; ++WalkInNum) {
                int WalkInID = TransSystem(TransSystemNum).WalkInNumMT(WalkInNum);
                print(state.files.eio,
                      "   Medium Temperature Refrigeration Walk In Cooler,{},{},{:.1R},{:.1R},{:.1R},{:.1R},{:.1R},{:.1R},{}\n",
                      WalkInID,
                      WalkIn(WalkInID).Name,
                      WalkIn(WalkInID).DesignRatedCap,
                      WalkIn(WalkInID).Temperature,
                      WalkIn(WalkInID).CoilFanPower,
                      WalkIn(WalkInID).CircFanPower,
                      WalkIn(WalkInID).DesignLighting,
                      WalkIn(WalkInID).HeaterPower,
                      WalkIn(WalkInID).DefrostCapacity,
                      WalkIn(WalkInID).NumZones);
                for (int ZoneID = 1; ZoneID <= WalkIn(WalkInID).NumZones; ++ZoneID) {
                    print(state.files.eio,
                          "      Walk-In Surfaces Facing Zone,{},{:.1R},{:.4R},{:.2R},{:.2R},{:.4R},{:.2R},{:.2R},{:.4R}\n",
                          WalkIn(WalkInID).ZoneName(ZoneID),
                          WalkIn(WalkInID).SurfaceArea(ZoneID),
                          WalkIn(WalkInID).UValue(ZoneID),
                          WalkIn(WalkInID).AreaStockDr(ZoneID),
                          WalkIn(WalkInID).HeightStockDr(ZoneID),
                          WalkIn(WalkInID).UValueStockDr(ZoneID),
                          WalkIn(WalkInID).AreaGlassDr(ZoneID),
                          WalkIn(WalkInID).HeightGlassDr(ZoneID),
                          WalkIn(WalkInID).UValueGlassDr(ZoneID));
                } // Num zones for each walk in on system
            } // NumWalkInsMT on system
            for (int WalkInNum = 1; WalkInNum <= TransSystem(TransSystemNum).NumWalkInsLT; ++WalkInNum) {
                int WalkInID = TransSystem(TransSystemNum).WalkInNumLT(WalkInNum);
                print(state.files.eio,
                      "   Low Temperature Refrigeration Walk In Cooler,{},{},{:.1R},{:.1R},{:.1R},{:.1R},{:.1R},{:.1R},{:.1R},{}\n",
                      WalkInID,
                      WalkIn(WalkInID).Name,
                      WalkIn(WalkInID).DesignRatedCap,
                      WalkIn(WalkInID).Temperature,
                      WalkIn(WalkInID).CoilFanPower,
                      WalkIn(WalkInID).CircFanPower,
                      WalkIn(WalkInID).DesignLighting,
                      WalkIn(WalkInID).HeaterPower,
                      WalkIn(WalkInID).DefrostCapacity,
                      WalkIn(WalkInID).NumZones);
                for (int ZoneID = 1; ZoneID <= WalkIn(WalkInID).NumZones; ++ZoneID) {
                    print(state.files.eio,
                          "      Walk-In Surfaces Facing Zone,{},{:.1R},{:.4R},{:.2R},{:.2R},{:.4R},{:.2R},{:.2R},{:.4R}\n",
                          WalkIn(WalkInID).ZoneName(ZoneID),
                          WalkIn(WalkInID).SurfaceArea(ZoneID),
                          WalkIn(WalkInID).UValue(ZoneID),
                          WalkIn(WalkInID).AreaStockDr(ZoneID),
                          WalkIn(WalkInID).HeightStockDr(ZoneID),
                          WalkIn(WalkInID).UValueStockDr(ZoneID),
                          WalkIn(WalkInID).AreaGlassDr(ZoneID),
                          WalkIn(WalkInID).HeightGlassDr(ZoneID),
                          WalkIn(WalkInID).UValueGlassDr(ZoneID));
                } // Num zones for each walk in on system
            } // NumWalkInsLT on system

            for (int CompressorNum = 1; CompressorNum <= TransSystem(TransSystemNum).NumCompressorsHP; ++CompressorNum) {
                int CompID = TransSystem(TransSystemNum).CompressorNumHP(CompressorNum);
                print(state.files.eio,
                      "   High Pressure Refrigeration Compressor,{},{},{:.0R}\n",
                      CompID,
                      Compressor(CompID).Name,
                      Compressor(CompID).NomCap);
            } // NumCompressorsHP
            for (int CompressorNum = 1; CompressorNum <= TransSystem(TransSystemNum).NumCompressorsLP; ++CompressorNum) {
                int CompID = TransSystem(TransSystemNum).CompressorNumLP(CompressorNum);
                print(state.files.eio,
                      "   Low Pressure Refrigeration Compressor,{},{},{:.0R}\n",
                      CompID,
                      Compressor(CompID).Name,
                      Compressor(CompID).NomCap);
            } // NumCompressorsLP

            if (TransSystem(TransSystemNum).NumGasCoolers >= 1) {
                int GasCoolerID = TransSystem(TransSystemNum).GasCoolerNum(1);
                print(state.files.eio,
                      "   Refrigeration GasCooler:Air-Cooled,{},{},{:.1R},{:.1R},{:.1R},{:.1R},{:.1R}\n",
                      GasCoolerID,
                      GasCooler(GasCoolerID).Name,
                      GasCooler(GasCoolerID).RatedOutletP,
                      GasCooler(GasCoolerID).RatedOutletT,
                      GasCooler(GasCoolerID).RatedApproachT,
                      GasCooler(GasCoolerID).RatedCapacity,
                      GasCooler(GasCoolerID).RatedFanPower);
            } // System(SystemNum)%NumGasCoolers >= 1

        } // NumTransRefrigSystems
    } //(NumTransRefrigSystems > 0)

    if (state.dataRefrigCase->NumSimulationSecondarySystems > 0) {
        print(state.files.eio, "#Secondary Refrigeration Systems,{}\n", state.dataRefrigCase->NumSimulationSecondarySystems);
        for (int SecondaryID = 1; SecondaryID <= state.dataRefrigCase->NumSimulationSecondarySystems; ++SecondaryID) {
            switch (Secondary(SecondaryID).FluidType) {
            case SecFluidType::AlwaysLiquid: {
                print(state.files.eio,
                      "Secondary Refrigeration System: Fluid Always Liquid,{},{},{},{},{},{:.1R},{:.2R},{:.2R},{:.3R},{:.3R}\n",
                      SecondaryID,
                      Secondary(SecondaryID).Name,
                      Secondary(SecondaryID).NumCases,
                      Secondary(SecondaryID).NumWalkIns,
                      Secondary(SecondaryID).FluidName,
                      Secondary(SecondaryID).CoolingLoadRated,
                      Secondary(SecondaryID).TEvapDesign,
                      Secondary(SecondaryID).TApproachDifRated,
                      Secondary(SecondaryID).TRangeDifRated,
                      Secondary(SecondaryID).PumpTotRatedPower);
            } break;
            case SecFluidType::PhaseChange: {
                print(state.files.eio,
                      "Secondary Refrigeration System: Liquid Overfeed,{},{},{},{},{},{:.1R},{:.2R},{:.2R},{:.3R},{:.3R}\n",
                      SecondaryID,
                      Secondary(SecondaryID).Name,
                      Secondary(SecondaryID).NumCases,
                      Secondary(SecondaryID).NumWalkIns,
                      Secondary(SecondaryID).FluidName,
                      Secondary(SecondaryID).CoolingLoadRated,
                      Secondary(SecondaryID).TEvapDesign,
                      Secondary(SecondaryID).TApproachDifRated,
                      Secondary(SecondaryID).CircRate,
                      Secondary(SecondaryID).PumpTotRatedPower);
            } break;
            default:
                break;
            }
            for (int CaseNum = 1; CaseNum <= Secondary(SecondaryID).NumCases; ++CaseNum) {
                int CaseID = Secondary(SecondaryID).CaseNum(CaseNum);
                if (RefrigCase(CaseID).ZoneNodeNum > 0) {
                    print(state.files.eio,
                          "  Refrigeration Case,{},{},{},{},{},{:.1R},{:.2R},{:.1R},{:.1R},{:.1R},{:.1R},{:.1R},{:.1R}\n",
                          CaseID,
                          RefrigCase(CaseID).Name,
                          RefrigCase(CaseID).ZoneName,
                          RefrigCase(CaseID).ZoneNodeNum,
                          state.dataLoopNodes->NodeID(RefrigCase(CaseID).ZoneNodeNum),
                          RefrigCase(CaseID).RateTotCapPerLength,
                          RefrigCase(CaseID).RatedLHR,
                          RefrigCase(CaseID).Temperature,
                          RefrigCase(CaseID).Length,
                          RefrigCase(CaseID).OperatingFanPower,
                          RefrigCase(CaseID).LightingPower,
                          RefrigCase(CaseID).AntiSweatPower,
                          RefrigCase(CaseID).DefrostPower);
                }
            } // NumCases on secondary on secondary system

            for (int WalkInNum = 1; WalkInNum <= Secondary(SecondaryID).NumWalkIns; ++WalkInNum) {
                int WalkInID = Secondary(SecondaryID).WalkInNum(WalkInNum);
                print(state.files.eio,
                      "  Walk In,{},{},{:.1R},{:.1R},{:.1R},{:.1R},{:.1R},{:.1R},{:.1R}\n",
                      WalkInID,
                      WalkIn(WalkInID).Name,
                      WalkIn(WalkInID).DesignRatedCap,
                      WalkIn(WalkInID).Temperature,
                      WalkIn(WalkInID).CoilFanPower,
                      WalkIn(WalkInID).CircFanPower,
                      WalkIn(WalkInID).DesignLighting,
                      WalkIn(WalkInID).HeaterPower,
                      WalkIn(WalkInID).DefrostCapacity);
                for (int ZoneID = 1; ZoneID <= WalkIn(WalkInID).NumZones; ++ZoneID) {
                    print(state.files.eio,
                          "    Walk In Surfaces Facing Zone,{},{:.1R},{:.4R},{:.2R},{:.2R},{:.4R},{:.2R},{:.2R},{:.4R}\n",
                          WalkIn(WalkInID).ZoneName(ZoneID),
                          WalkIn(WalkInID).SurfaceArea(ZoneID),
                          WalkIn(WalkInID).UValue(ZoneID),
                          WalkIn(WalkInID).AreaStockDr(ZoneID),
                          WalkIn(WalkInID).HeightStockDr(ZoneID),
                          WalkIn(WalkInID).UValueStockDr(ZoneID),
                          WalkIn(WalkInID).AreaGlassDr(ZoneID),
                          WalkIn(WalkInID).HeightGlassDr(ZoneID),
                          WalkIn(WalkInID).UValueGlassDr(ZoneID));
                } // zones for walk ins on secondary
            } // walk ins on secondary

            for (int CoilNum = 1; CoilNum <= Secondary(SecondaryID).NumCoils; ++CoilNum) {
                int CoilID = Secondary(SecondaryID).CoilNum(CoilNum);
                print(state.files.eio, "   Air Chiller Load,{},{},{}\n", WarehouseCoil(CoilID).Name, CoilID, WarehouseCoil(CoilID).ZoneName);
            } // numairchillers
        } // secondary
    } // numsimulationsecondarys

    if (state.dataRefrigCase->NumRefrigChillerSets > 0) {
        print(state.files.eio, "#ZoneHVAC/Refrigeration Air Chiller Sets,{}\n", state.dataRefrigCase->NumRefrigChillerSets);
        for (int ChillerSetNum = 1; ChillerSetNum <= state.dataRefrigCase->NumRefrigChillerSets; ++ChillerSetNum) {
            print(state.files.eio,
                  "ZoneHVAC/Refrigeration Air Chiller Set,{},{},{},{}\n",
                  AirChillerSet(ChillerSetNum).Name,
                  ChillerSetNum,
                  AirChillerSet(ChillerSetNum).NumCoils,
                  AirChillerSet(ChillerSetNum).ZoneName);

            for (int CoilNum = 1; CoilNum <= AirChillerSet(ChillerSetNum).NumCoils; ++CoilNum) {
                int CoilID = AirChillerSet(ChillerSetNum).CoilNum(CoilNum);
                print(state.files.eio,
                      "   Refrigeration Air Chiller,{},{},{},{},{},{:.1R},{:.2R},{:.1R},{:.1R},{:.1R},{:.1R},{:.1R},{:.1R}\n",
                      CoilID,
                      WarehouseCoil(CoilID).Name,
                      WarehouseCoil(CoilID).ZoneName,
                      WarehouseCoil(CoilID).ZoneNodeNum,
                      state.dataLoopNodes->NodeID(WarehouseCoil(CoilID).ZoneNodeNum),
                      WarehouseCoil(CoilID).UnitLoadFactorSens,
                      WarehouseCoil(CoilID).RatedSensibleCap,
                      WarehouseCoil(CoilID).TEvapDesign,
                      WarehouseCoil(CoilID).RatedTemperatureDif,
                      WarehouseCoil(CoilID).RatedFanPower,
                      WarehouseCoil(CoilID).HeaterPower,
                      WarehouseCoil(CoilID).DefrostCapacity,
                      WarehouseCoil(CoilID).RatedAirVolumeFlow);
            } // numairchillers
        } // DataHeatBalance::NumRefrigChillerSets
    } // DataHeatBalance::NumRefrigChillerSets
}

void WalkInData::CalculateWalkIn(EnergyPlusData &state) // Absolute pointer to  Walk In
{

    // SUBROUTINE INFORMATION:
    //       AUTHOR         Therese Stovall, ORNL, May 2009
    //       DATE WRITTEN   Oct/Nov 2004
    //       MODIFIED       na
    //       RE-ENGINEERED  na

    // PURPOSE OF THIS SUBROUTINE:
    // To model Walk In Coolers.

    // METHODOLOGY EMPLOYED:
    // Walk-in cooler performance is based on the ASHRAE load model, which includes
    // infiltration through door openings and sensible loss through walls/ceilings identified
    // by the user as sum of UA for each zone. A sub-floor heater is assumed to be sized so that
    // the temperature of the slab beneath the floor insulation is the same as the ground
    // temperature (to avoid ground freezing and heaving).
    // All equipment loads (fan, light, heaters) are modeled as well.  Sensible and latent
    // exchange with multiple adjoining zones is included. A master schedule is used for the Walk In operation and
    // additional schedules control the lights, defrost, and heater operation.

    // The fan is assumed to be off for Hot-Gas, Hot-Brine, and Electric defrost. The user can choose
    // to include the load due to bringing the coil mass up from the evaporating temperature to the melting temperature
    //  if they choose.  Otherwise this factor is set to zero.

    // Unmet loads are accumulated to be met the following time step.  This usually occurs during defrost and
    // restocking.

    // REFERENCES:
    // ASHRAE 2006 Handbook, chapters 13 and 14.
    // Gosney, W.B., Olama, G.A.-L., Heat and Enthalpy Gains through Cold Room Doorways,
    //     Proceedings of the Institute of Refrigeration, vol. 72, pp 31-41, 1975

    Real64 constexpr DefaultWalkInDoorOpenFactor(0.05); // walk in door open factor (fraction time open)

    static constexpr std::string_view RoutineName("CalculateWalkIn");
    Real64 CapApplied(0.0);          // Walk In total capacity at specific operating conditions
    Real64 DefrostSchedule(0.0);     // WalkIn defrost schedule, between 0 and 1
    Real64 DefrostEnergyNeeded(0.0); // Energy needed to melt all ice, used with temperature termination (J)
    Real64 DensityFactorFm(0.0);     // called Fm in ASHRAE 2010 eq 13 page 24.5 for door infiltration
    Real64 DensitySqRtFactor(0.0);   // from ASHRAE 2010 eq 12 page 24.4 for door infiltration

    // Current value of WalkIn operating (availability) schedule
    Real64 WalkInSchedule = this->availSched->getCurrentVal();
    if (WalkInSchedule <= 0) {
        return;
    }
    // GET OTHER SCHEDULES
    DefrostSchedule = this->defrostSched->getCurrentVal();
    Real64 DefrostDripDownSchedule = this->defrostDripDownSched->getCurrentVal();
    // next statement In case user doesn't understand concept of drip down schedule
    DefrostDripDownSchedule = max(DefrostDripDownSchedule, DefrostSchedule);

    // next four values optional, so set to default before checking for schedule
    Real64 StockingLoad = (this->stockingSched != nullptr) ? this->stockingSched->getCurrentVal() : 0.0;
    Real64 LightingSchedule = (this->lightingSched != nullptr) ? this->lightingSched->getCurrentVal() : 1.0;
    Real64 HeaterSchedule = (this->heaterSched != nullptr) ? this->heaterSched->getCurrentVal() : 1.0;
    Real64 CircFanSchedule = (this->circFanAvailSched != nullptr) ? this->circFanAvailSched->getCurrentVal() : 1.0;

    // Set local subroutine variables for convenience
    Real64 TWalkIn = this->Temperature; // WalkIn operating temperature (C)

    // Enthalpy of air corresponding to walk in temperature and 90% assumed RH (J/kg)
    Real64 EnthalpyAirWalkIn = Psychrometrics::PsyHFnTdbRhPb(state, TWalkIn, 0.9, state.dataEnvrn->OutBaroPress); // assume 90%RH in cooler

    // corresponds to walk in temp and 90% assumed RH(kg water/kg dry air)
    Real64 HumRatioAirWalkIn = Psychrometrics::PsyWFnTdbH(state, TWalkIn, EnthalpyAirWalkIn);
    Real64 DensityAirWalkIn = Psychrometrics::PsyRhoAirFnPbTdbW(state, state.dataEnvrn->OutBaroPress, TWalkIn, HumRatioAirWalkIn);
    Real64 Conv = state.dataEnvrn->Latitude * 2.0 * Constant::Pi / 360.0; // Convert DataEnvironment::Latitude to radians
    Real64 Gravity = 9.780373 * (1.0 + 0.0052891 * pow_2(std::sin(Conv)) - 0.0000059 * pow_2(std::sin(2.0 * Conv)));

    // CALCULATE ALL LOADS INFLUENCED BY ZONE TEMPERATURE AND RH
    // set to zero before summing over zones
    Real64 SensibleLoadTotal(0.0); // Total sensible load on WalkIn over all zones (W)
    Real64 LatentLoadTotal(0.0);   // total latent load on WalkIn over all zones (W)
    Real64 ZoneLatentLoad(0.0);    // Latent WalkIn credit delivered to zone (W)

    this->SensZoneCreditRate = 0.0;
    this->SensZoneCreditCoolRate = 0.0;
    this->SensZoneCreditCool = 0.0;
    this->SensZoneCreditHeatRate = 0.0;
    this->SensZoneCreditHeat = 0.0;
    this->LatZoneCreditRate = 0.0;

    // Start zone loop:
    for (int ZoneID = 1; ZoneID <= this->NumZones; ++ZoneID) {
        int zoneNum = this->ZoneNum(ZoneID);
        int zoneNodeNum = this->ZoneNodeNum(ZoneID);
        Real64 ZoneDryBulb = state.dataLoopNodes->Node(zoneNodeNum).Temp; // Dry Bulb Temperature of adjacent zone
        Real64 WalkInLatLoad = -ZoneLatentLoad;                           // Walk in cooler latent load facing particular zone (W)
        Real64 DelTemp = ZoneDryBulb - TWalkIn;                           // Difference between zone and walk in temperatures (C)
        Real64 StockDoorArea = this->AreaStockDr(ZoneID);
        Real64 GlassDoorArea = this->AreaGlassDr(ZoneID);                          // facing a particular zone (m2)
        Real64 UAOtherSurfaces = this->SurfaceArea(ZoneID) * this->UValue(ZoneID); // UA for non-door surfaces facing a certain zone (W/C)
        Real64 ZInfilSensLoad(0.0);                                                // Sensible load due to infiltration in one zone
        Real64 ZdoorSensLoad(0.0);                                                 // Sensible load due to UA delta T through closed door in one zone

        // Derate compared to fully developed flow through 100% open door
        Real64 DoorFlowFactor = 0.8; // see ASHRAE Refrigeration, p13.5, 2006
        if (DelTemp <= 11.0) {
            DoorFlowFactor = 1.1; // from ASHRAE Refrigeration Loads
        }

        // Get infiltration loads if either type of door is present in this zone
        if (StockDoorArea > 0.0 || GlassDoorArea > 0.0) {
            // Zone relative humidity fraction (decimal)
            Real64 ZoneRHFrac = Psychrometrics::PsyRhFnTdbWPb(state,
                                                              state.dataLoopNodes->Node(zoneNodeNum).Temp,
                                                              state.dataLoopNodes->Node(zoneNodeNum).HumRat,
                                                              state.dataEnvrn->OutBaroPress,
                                                              RoutineName);
            // Enthalpy of the air in a particular zone (J/kg)
            Real64 EnthalpyZoneAir = Psychrometrics::PsyHFnTdbRhPb(state, ZoneDryBulb, ZoneRHFrac, state.dataEnvrn->OutBaroPress, RoutineName);
            Real64 HumRatioZoneAir = Psychrometrics::PsyWFnTdbH(state, ZoneDryBulb, EnthalpyZoneAir, RoutineName);
            Real64 DensityZoneAir =
                Psychrometrics::PsyRhoAirFnPbTdbW(state, state.dataEnvrn->OutBaroPress, ZoneDryBulb, HumRatioZoneAir, RoutineName);
            if (DensityZoneAir < DensityAirWalkIn) { // usual case when walk in is colder than zone
                DensitySqRtFactor = std::sqrt(1.0 - DensityZoneAir / DensityAirWalkIn);
                DensityFactorFm = std::pow(2.0 / (1.0 + std::pow(DensityAirWalkIn / DensityZoneAir, 0.333)), 1.5);
            } else { // temperature inversion with zone colder and/or drier than walk-in, infiltration in reverse direction
                // The enthalpy difference will show whether the energy transport is reversed
                //(same air mass exchange in either direction )
                // That is, these factors establish the magnitude of the exchange air flow, not direction
                DensitySqRtFactor = std::sqrt(1.0 - DensityAirWalkIn / DensityZoneAir);
                DensityFactorFm = std::pow(2.0 / (1.0 + std::pow(DensityZoneAir / DensityAirWalkIn, 0.333)), 1.5);
            } // check for density in zone and in walk-in to avoid taking sqrt of neg number

            Real64 StockDoorInfLoad = 0.0;  // infiltration through stock doors in a particular zone (W)
            Real64 StockDoorSensHeat = 0.0; // sensible heat gain through stock doors (UA*delta T) (W)
            Real64 DoorProtectEff(0.0);     // Door protection effectiveness
            Real64 DrHeight(0.0);           // Door height (m)
            Real64 DrArea(0.0);             // Door area (m2)
            Real64 FullFlowInfLoad(0.0);    // Total load (lat + sens) due to 100% open doors w/ fully developed flow (W)

            if (StockDoorArea > 0.0) {
                std::array<Real64, (int)WIStockDoor::Num> doorProtectEffs = {0.0, 0.5, 0.9}; // Values from ASHRAE Ref p 13.6
                DoorProtectEff = doorProtectEffs[(int)this->StockDoorProtectType(ZoneID)];
                DrHeight = this->HeightStockDr(ZoneID);
                DrArea = StockDoorArea;
                // if exists, get Stock Door Zone schedule
                Real64 DoorOpenFactor = DefaultWalkInDoorOpenFactor;
                if (this->stockDoorOpenScheds(ZoneID) != nullptr) {
                    DoorOpenFactor = this->stockDoorOpenScheds(ZoneID)->getCurrentVal();
                }

                FullFlowInfLoad = 0.221 * DrArea * (EnthalpyZoneAir - EnthalpyAirWalkIn) * DensityAirWalkIn * DensitySqRtFactor *
                                  std::sqrt(Gravity * DrHeight) * DensityFactorFm;
                StockDoorInfLoad = FullFlowInfLoad * DoorOpenFactor * DoorFlowFactor * (1.0 - DoorProtectEff);
                StockDoorSensHeat = DrArea * this->UValueStockDr(ZoneID) * DelTemp;
            } // have stock doors

            Real64 GlassDoorSensHeat(0.0); // sensible heat gain through glass reach-in doors (UA*delta T) (W)
            Real64 GlassDoorInfLoad = 0.0; // infiltration through glass reach-in doors in a particular zone (W)

            if (GlassDoorArea > 0.0) {
                DoorProtectEff = 0.5; // Assume glass doors have air curtain
                DrHeight = this->HeightGlassDr(ZoneID);
                DrArea = GlassDoorArea;
                // get Glass Door Zone schedule
                Real64 DoorOpenFactor = DefaultWalkInDoorOpenFactor; // default value
                if (this->glassDoorOpenScheds(ZoneID) != nullptr) {
                    DoorOpenFactor = this->glassDoorOpenScheds(ZoneID)->getCurrentVal();
                }

                FullFlowInfLoad = 0.221 * DrArea * (EnthalpyZoneAir - EnthalpyAirWalkIn) * DensityAirWalkIn * DensitySqRtFactor *
                                  std::sqrt(Gravity * DrHeight) * DensityFactorFm;
                GlassDoorInfLoad = FullFlowInfLoad * DoorOpenFactor * DoorFlowFactor * (1.0 - DoorProtectEff);
                GlassDoorSensHeat = DrArea * this->UValueGlassDr(ZoneID) * DelTemp;
            } // have Glass doors

            // assume mass dry air infiltrating into walk-in == mass out into zone,
            //                       that is, equal air exchange (ASHRAE 2006 Refrigeration)
            Real64 ZoneInfilLoad = -StockDoorInfLoad - GlassDoorInfLoad; // Walk in cooler infiltration load (sens + latent) in certain zone (W)
            Real64 MassDryAirRate =
                -ZoneInfilLoad / (EnthalpyZoneAir - EnthalpyAirWalkIn); // Mass dry air infiltrating into/out-of walkin through doors (kg/s)
            Real64 WaterRemovRate =
                MassDryAirRate * (HumRatioZoneAir - HumRatioAirWalkIn); // Walk in cooler removes water at this rate in this zone (kg/s)
            // Just as with cases,  we assume no latent credit (water removal = 0) to zone or load on cooler during dripdown
            // To be consistent with the treatment of refrigerated cases, latent load
            //  and latent credit are both based on reducing the infiltrating vapor to ice.  (This is
            //  slightly greater than if the latent credit were based upon condensing out the water as liquid.)
            //  then it would be: ZoneLatentLoad = -WaterRemovRate * WaterToVaporEnthalpy * (1.0d0-DefrostDripDownSchedule)
            ZoneLatentLoad = -WaterRemovRate * IcetoVaporEnthalpy * (1.0 - DefrostDripDownSchedule);
            ZInfilSensLoad = ZoneInfilLoad - (-WaterRemovRate * IcetoVaporEnthalpy); // done to avoid moving latent to sens during dripdown
            ZdoorSensLoad = -GlassDoorSensHeat - StockDoorSensHeat;
            WalkInLatLoad = -ZoneLatentLoad;
            if (this->TEvapDesign <= 0.0) { // water turned to ice on coil
                WalkInLatLoad = WaterRemovRate * IcetoVaporEnthalpy * (1.0 - DefrostDripDownSchedule);
                // FROST:  keep track of frost build up on evaporator coil
                //         avoid accumulation during warm-up to avoid reverse dd test problem
                if (!state.dataGlobal->WarmupFlag) {
                    Real64 FrostChangekg = (WaterRemovRate * state.dataGlobal->TimeStepZoneSec) * (1.0 - DefrostDripDownSchedule);
                    this->KgFrost += FrostChangekg;
                }
            } // water to ice
        } // No doors

        // Sensible WalkIn credit delivered to a particular zone (W)
        Real64 ZoneSensLoad = ZInfilSensLoad + ZdoorSensLoad - UAOtherSurfaces * DelTemp;
        Real64 WalkInSensLoad = -ZoneSensLoad; // Walk in cooler sensible load facing particular zone (W)

        // Update globals for use in ZoneTemperaturePredictorCorrector (Air Heat Balance) and
        //   Zone Equipment Manager. Sum walk-in credits to zone using existing 'casecredit' variable
        //   No return air fractions are applied to walk-ins, and no latent in stocking -

        state.dataHeatBal->RefrigCaseCredit(zoneNum).SenCaseCreditToZone += ZoneSensLoad;
        state.dataHeatBal->RefrigCaseCredit(zoneNum).LatCaseCreditToZone += ZoneLatentLoad;

        // Set up report variables for each zone for this walk-in
        // Sensible heat exchange can be positive or negative, split into separate output variables and always report positive value
        this->SensZoneCreditRate(ZoneID) = ZoneSensLoad;
        if (ZoneSensLoad <= 0.0) {
            this->SensZoneCreditCoolRate(ZoneID) = -ZoneSensLoad;
            this->SensZoneCreditCool(ZoneID) = -ZoneSensLoad * state.dataGlobal->TimeStepZoneSec;
            this->SensZoneCreditHeatRate(ZoneID) = 0.0;
            this->SensZoneCreditHeat(ZoneID) = 0.0;
        } else {
            this->SensZoneCreditHeatRate(ZoneID) = ZoneSensLoad;
            this->SensZoneCreditHeat(ZoneID) = ZoneSensLoad * state.dataGlobal->TimeStepZoneSec;
            this->SensZoneCreditCoolRate(ZoneID) = 0.0;
            this->SensZoneCreditCool(ZoneID) = 0.0;
        }
        // This rate should always be negative
        this->LatZoneCreditRate(ZoneID) = ZoneLatentLoad;
        this->LatZoneCredit(ZoneID) = ZoneLatentLoad * state.dataGlobal->TimeStepZoneSec;

        // Running total over all zones, use later to dispatch capacity
        SensibleLoadTotal += WalkInSensLoad;
        LatentLoadTotal += WalkInLatLoad;

    } // Do loop over zones for zone-condition-related sensible and latent loads

    // cooling coil fan power default is 375W, = 1/2 HP (Tyler showed 1/3 to 3/4 hp)

    // CALCULATE AUX LOADS DUE TO LIGHTS, FANS AND HEATERS
    Real64 LightLoad = this->DesignLighting * LightingSchedule; // Total lighting energy rate (W)
    // turn coil fan off during defrost/drip - down period

    // Total fan energy rate (W)
    Real64 FanLoad = this->CircFanPower * CircFanSchedule + this->CoilFanPower * (1.0 - DefrostDripDownSchedule);
    Real64 HeaterLoad = this->HeaterPower * HeaterSchedule; // Total heater (except defrost) energy rate (W)
    // Calculate floor load - using 'DataEnvironment::GroundTemp' assigned in weather manager (can be entered by user if desired)
    //    Default value is 18C.
    // Total floor energy rate (W)
    Real64 FloorLoad =
        this->FloorArea * this->FloorUValue * (state.dataEnvrn->GroundTemp[(int)DataEnvironment::GroundTempType::BuildingSurface] - TWalkIn);

    Real64 DefrostLoad;

    // DEFROST CALCULATIONS
    if ((DefrostSchedule > 0.0) && (this->defrostType != DefrostType::None) && (this->defrostType != DefrostType::OffCycle)) {
        DefrostLoad = this->DefrostCapacity * DefrostSchedule;                  // W
        Real64 StartFrostKg = this->KgFrost;                                    // frost load at start of time step (kg of ice)
        Real64 DefrostEnergy = DefrostLoad * state.dataGlobal->TimeStepZoneSec; // Joules
        if (this->DefrostControlType == DefrostCtrlType::TempTerm) {
            //  Need to turn defrost system off early if controlled by temperature and all ice melted
            //  For temperature termination, need to recognize not all defrost heat goes to melt ice
            //  Some goes to misc losses (for fluid defrost, some coil areas bare earlier than
            //  others and xfer heat to environment)
            //  Assume full ice melting satisfies temperature control.
            //      (defaults for DefEnergyFraction are :=0.7 for elec, =0.3 for fluids)
            Real64 AvailDefrostEnergy = this->DefEnergyFraction * DefrostEnergy; // Joules avail to melt ice
            Real64 IceSensHeatNeeded = 0.0; // Energy to raise frost temperature to 0C, used w/ temp termination (J)
            if (StartFrostKg > 0.0) {
                if (this->IceTemp < 0.0) {
                    Real64 StartIceTemp = this->IceTemp;                                       // Frost temperature at start of time step [C]
                    IceSensHeatNeeded = StartFrostKg * SpecificHeatIce * (0.0 - StartIceTemp); // Joules
                    if (AvailDefrostEnergy >= IceSensHeatNeeded) {
                        this->IceTemp = 0.0;
                        AvailDefrostEnergy -= IceSensHeatNeeded; // Joules
                    } else {                                     // DefrostEnergy < IceSensHeatNeeded
                        this->IceTemp = StartIceTemp + AvailDefrostEnergy / (SpecificHeatIce * StartFrostKg);
                        AvailDefrostEnergy = 0.0;
                    } // AvailDefrostEnergy >= IceSensHeatNeeded
                } // IceTemp < 0,  need to raise temperature of ice
                // Reduce defrost heat load on walkin by amount of ice melted during time step
                Real64 FrostChangekg = min(AvailDefrostEnergy / IceMeltEnthalpy, StartFrostKg);
                if (FrostChangekg < StartFrostKg) {
                    DefrostLoad -= FrostChangekg * IceMeltEnthalpy / state.dataGlobal->TimeStepZone / Constant::rSecsInHour;
                    if (!state.dataGlobal->WarmupFlag) {
                        this->KgFrost = StartFrostKg - FrostChangekg;
                    }
                    // DefrostSchedule not changed
                } else { // all frost melted during time step, so need to terminate defrost
                    //  see Aug 8 page 3 notes
                    this->KgFrost = 0.0;
                    DefrostEnergyNeeded = (IceSensHeatNeeded + (FrostChangekg * IceMeltEnthalpy)) /
                                          this->DefEnergyFraction; // Joules - energy needed including E unavail to melt ice
                    DefrostSchedule = min(DefrostSchedule, (DefrostEnergyNeeded / (this->DefrostCapacity * state.dataGlobal->TimeStepZoneSec)));
                    // reduce load on walkin by energy put into ice melting
                    DefrostLoad = max(0.0,
                                      (DefrostSchedule * this->DefrostCapacity -
                                       (IceSensHeatNeeded + (FrostChangekg * IceMeltEnthalpy)) / state.dataGlobal->TimeStepZoneSec));
                    this->IceTemp = this->TEvapDesign;

                } // frost melted during time step less than amount of ice at start
            } else { // no frost present so terminate defrost and reset ice temperature for start of next defrost
                DefrostLoad = 0.0;
                DefrostSchedule = 0.0;
                this->IceTemp = this->TEvapDesign;
            } // have frost present

        } else { // Not temperature control type
            Real64 FrostChangekg = min(DefrostEnergy / IceMeltEnthalpy, StartFrostKg);
            // Reduce defrost heat load on walkin by amount of ice melted during time step
            DefrostLoad -= FrostChangekg * IceMeltEnthalpy / state.dataGlobal->TimeStepZone / Constant::rSecsInHour;
            if (!state.dataGlobal->WarmupFlag) {
                this->KgFrost = StartFrostKg - FrostChangekg;
            }
            // DefrostSchedule not changed
        } // Temperature termination control type

    } else { // DefrostSchedule <= 0 or have None or OffCycle
        DefrostLoad = 0.0;
    } // Defrost calculations

    if (this->defrostType == DefrostType::Elec) {
        this->ElecDefrostConsumption = this->DefrostCapacity * DefrostSchedule * state.dataGlobal->TimeStepZoneSec;
        this->ElecDefrostPower = this->DefrostCapacity * DefrostSchedule;
    } else {
        this->ElecDefrostConsumption = 0.0;
        this->ElecDefrostPower = 0.0;
    }

    // If hot brine or hot gas is used for defrost, need to reduce condenser load by heat reclaimed for defrost
    if (this->defrostType == DefrostType::Fluid) {
        this->HotDefrostCondCredit = this->DefrostCapacity * DefrostSchedule;
    }

    // loads reflects that walk ins continue to accumulate loads, even during defrost
    // but cap is used to report portion met by active system while operating

    //*** See if capacity meets load and manage accumulated stored energy ***********************************
    SensibleLoadTotal += LightLoad + HeaterLoad + FanLoad + StockingLoad + DefrostLoad + FloorLoad;
    Real64 LoadTotal = SensibleLoadTotal + LatentLoadTotal; // total load in time step (W)

    // Account for difference between load and capacity. Assume rack or system able to provide
    // rated capacity.  If it can't, that unmet energy will be stored and discharged at the system level.
    //  Here we are calculating the load the walk-in cooler places on the refrigeration compressor systems.
    //  Meet current load to the extent possible.  If extra capacity available,
    //  apply it to previously unmet/stored loads.  If capacity less than current load,
    //  (e.g. as it is during defrost cycles) save the unmet/stored load to be met in
    //  succeeding time steps. This is an artificial way of recognizing that the internal
    //  temperature will increase by a small amount during defrost and the system will have to
    //  run full out until the temperature is brought back down.

    // Rate needed to serve all stored energy during single time step (W)
    Real64 StoredEnergyRate = this->StoredEnergy / state.dataGlobal->TimeStepZone / Constant::rSecsInHour;
    Real64 LoadRequested = LoadTotal + StoredEnergyRate; // Load necessary to meet current and all stored energy needs (W)

    Real64 LatentCapApplied;        // Walk In latent capacity at specific operating conditions
    Real64 SensibleCapApplied(0.0); // Walk In sensible capacity at specific operating conditions

    // prorate available cooling capacity for portion of time off due to drip down.
    Real64 MaxCap = this->DesignRatedCap * (1.0 - DefrostDripDownSchedule); // Design chilling capacity reduced according to drip-down schedule (W)

    if (MaxCap >= LoadRequested) {
        // Have more at least as much capacity available as needed, even counting stored energy
        CapApplied = LoadRequested;
        SensibleCapApplied = SensibleLoadTotal + StoredEnergyRate;
        LatentCapApplied = LatentLoadTotal;
        this->StoredEnergy = 0.0;
    } else {
        // Don't have as much capacity as needed (during dripdown or period following dripdown)
        CapApplied = MaxCap;
        LatentCapApplied = min(LatentLoadTotal, MaxCap); // Latent load should never be > capavail, but just in case...
        SensibleCapApplied = CapApplied - LatentCapApplied;
        if (!state.dataGlobal->WarmupFlag) {
            this->StoredEnergy += (LoadTotal - MaxCap) * state.dataGlobal->TimeStepZoneSec;
        }
    } // CapAvail vs Load requested

    // ReportWalkIn( WalkInID)
    this->TotalCoolingLoad = CapApplied;
    this->TotalCoolingEnergy = CapApplied * state.dataGlobal->TimeStepZoneSec;
    this->TotSensCoolingEnergyRate = SensibleCapApplied;
    this->TotSensCoolingEnergy = SensibleCapApplied * state.dataGlobal->TimeStepZoneSec;
    this->TotLatCoolingEnergyRate = LatentCapApplied;
    this->TotLatCoolingEnergy = LatentCapApplied * state.dataGlobal->TimeStepZoneSec;

    this->ElecFanPower = FanLoad;
    this->ElecFanConsumption = FanLoad * state.dataGlobal->TimeStepZoneSec;
    this->ElecHeaterPower = HeaterLoad;
    this->ElecHeaterConsumption = HeaterLoad * state.dataGlobal->TimeStepZoneSec;
    this->ElecLightingPower = LightLoad;
    this->ElecLightingConsumption = LightLoad * state.dataGlobal->TimeStepZoneSec;
    this->TotalElecPower = FanLoad + HeaterLoad + LightLoad + this->ElecDefrostPower;
    this->TotalElecConsumption = this->TotalElecPower * state.dataGlobal->TimeStepZoneSec;

    //**************************************************************************************************
    // Cap Energy and Kg Frost to avoid floating overflow errors
    // 1-time warning is issued. It should be rare but could happen with unrealistic inputs.
    if (this->StoredEnergy > MyLargeNumber) {
        this->StoredEnergy = MyLargeNumber;
        if (this->ShowUnmetWIEnergyWarning) {
            ShowWarningError(state, format("Refrigeration:WalkIn: {}", this->Name));
            ShowContinueError(state, " This walk-in cooler has insufficient capacity to meet the loads");
            ShowContinueError(state,
                              format("... Occurrence info = {}, {} {}",
                                     state.dataEnvrn->EnvironmentName,
                                     state.dataEnvrn->CurMnDy,
                                     General::CreateSysTimeIntervalString(state)));
            ShowContinueError(state, " Refer to documentation for further explanation of Total Cooling Capacity.");
            this->ShowUnmetWIEnergyWarning = false;
        } // ShowStoreEnergyWarning
    } // stored energy > large number
    if (this->KgFrost > MyLargeNumber) {
        this->KgFrost = MyLargeNumber;
        if (this->ShowWIFrostWarning) {
            ShowWarningError(state, format("Refrigeration:WalkIn: {}", this->Name));
            ShowContinueError(state, " This walkin cooler has insufficient defrost capacity to remove the excess frost accumulation.");
            ShowContinueError(state, " Check the defrost schedule or defrost capacity. ");
            ShowContinueError(state,
                              format("... Occurrence info = {}, {} {}",
                                     state.dataEnvrn->EnvironmentName,
                                     state.dataEnvrn->CurMnDy,
                                     General::CreateSysTimeIntervalString(state)));
            this->ShowWIFrostWarning = false;
        }
    }
}

void SecondaryLoopData::CalculateSecondary(EnergyPlusData &state, int const SecondaryNum)
{
    // SUBROUTINE INFORMATION:
    //       AUTHOR         Therese Stovall, ORNL
    //       DATE WRITTEN   Spring 2009
    //       RE-ENGINEERED  na

    // PURPOSE OF THIS SUBROUTINE:
    // Find the total cooling load, pump power, and needed primary refrigerant supply temperature
    // for a secondary system.

    // METHODOLOGY EMPLOYED:
    // Sum the loads for the cases and walk-ins supplied by a secondary loop.
    // Calculate the pumping power.
    // Assume that the fluid supply and return temperatures are fixed and the
    // fluid flow rate is varied to meed the variable load.
    // User has been told in IO and Eng ref: for secondary systems/pumps: pump energy is f(viscosity),
    //        but since specifying Tcircfluid as steady
    //        state in loop, specify power for fluid and system head/resistance at that temp
    // ashrae 2006 p4.1 supports 78% eff for pump impellers
    //  all power into heat because it would otherwise not be counted in zone
    //  if use semihermetic motor, also need to add motor ineff as heat

    // REFERENCES:
    // SCE report
    //  others

    Real64 constexpr ErrorTol(0.001); // Iterative solution tolerance

    bool AtPartLoad;          // Whether or not need to iterate on pump power
    bool DeRate;              // If true, need to derate aircoils because don't carry over unmet energy
    int Iter;                 // loop counter
    Real64 CpBrine;           // Specific heat (W/kg)
    Real64 DensityBrine;      // Density (kg/m3)
    Real64 DiffTemp;          // (C)
    Real64 distPipeHeatGain;  // Optional (W)
    Real64 Error;             // Used in iterative soln for pumps needed to meet load (that has to include pump energy)
    Real64 FlowVolNeeded;     // Flow rate needed to meet load (m3/s)
    Real64 PartLdFrac;        // Used to ratio pump power
    Real64 PartPumpFrac;      // Used to see if part pumps dispatched meets part pump load
    Real64 PrevTotalLoad;     // Used in pump energy convergence test
    Real64 RefrigerationLoad; // Load for cases and walk-ins served by loop, does not include pump energy (W)
    Real64 StoredEnergyRate;  // Used to meet loads unmet in previous time step (related to defrost cycles
    //     on cases/walk-ins served)(W)
    Real64 TBrineIn;                  // Brine temperature going to heat exchanger, C
    Real64 TotalHotDefrostCondCredit; // Used to credit condenser when heat reclaim used for hot gas/brine defrost (W)
    Real64 TotalPumpPower;            // Total Pumping power for loop, W
    Real64 TotalLoad;                 // Total Cooling Load on secondary loop, W
    Real64 TPipesReceiver(0.0);       // Temperature used for contents of pipes and/or receiver in calculating shell losses (C)
    Real64 VarFrac;                   // Pump power fraction for variable speed pump, dimensionless
    Real64 VolFlowRate;               // Used in dispatching pumps to meet load (m3/s)

    auto &RefrigCase = state.dataRefrigCase->RefrigCase;
    auto &WalkIn = state.dataRefrigCase->WalkIn;
    auto &WarehouseCoil = state.dataRefrigCase->WarehouseCoil;

    Real64 localTimeStep = (state.dataRefrigCase->UseSysTimeStep) ? state.dataHVACGlobal->TimeStepSys : state.dataGlobal->TimeStepZone;
    Real64 localTimeStepSec = localTimeStep * Constant::rSecsInHour;

    switch (this->FluidType) {
    case SecFluidType::AlwaysLiquid: {
        CpBrine = this->CpBrineRated;
        DensityBrine = this->DensityBrineRated;
        TBrineIn = this->TBrineInRated;
        TPipesReceiver = this->TBrineAverage;
    } break;
    case SecFluidType::PhaseChange: {
        TPipesReceiver = this->TCondense;
    } break;
    default:
        break;
    } // Fluid type

    // Initialize this secondary for this time step
    TotalPumpPower = 0.0;
    RefrigerationLoad = 0.0;
    TotalHotDefrostCondCredit = 0.0;
    FlowVolNeeded = 0.0;
    DeRate = false;

    // SCE page 28 gives a delta T for pipe heat gains
    //         (.25F each for supply and discharge) for use with mdot*cp.
    //          However, another author shows this as a major diff between dx and secondary
    //          So - allow the user to include this in his total load, even though he has to do
    //          most of the calculations before the input (to get to SumUADistPiping)).
    distPipeHeatGain = 0.0;
    if (this->SumUADistPiping > MySmallNumber) {
        int ZoneNodeNum = this->DistPipeZoneNodeNum;
        DiffTemp = state.dataLoopNodes->Node(ZoneNodeNum).Temp - TPipesReceiver;
        distPipeHeatGain = DiffTemp * this->SumUADistPiping;
        // pipe heat load is a positive number (ie. heat absorbed by pipe, so needs to be subtracted
        //     from refrigcasecredit (- for cooling zone, + for heating zone)
        this->DistPipeZoneHeatGain = -distPipeHeatGain;
        state.dataHeatBal->RefrigCaseCredit(this->DistPipeZoneNum).SenCaseCreditToZone -= distPipeHeatGain;
    } // calc distribution piping heat gains

    Real64 receiverHeatGain = 0.0;
    if (this->SumUAReceiver > MySmallNumber) {
        int ZoneNodeNum = this->ReceiverZoneNodeNum;
        DiffTemp = state.dataLoopNodes->Node(ZoneNodeNum).Temp - TPipesReceiver;
        receiverHeatGain = DiffTemp * this->SumUAReceiver;
        // receiver heat load is a positive number (ie. heat absorbed by receiver, so needs to be subtracted
        //     from refrigcasecredit (- for cooling zone, + for heating zone)
        this->ReceiverZoneHeatGain = -receiverHeatGain;
        state.dataHeatBal->RefrigCaseCredit(this->ReceiverZoneNum).SenCaseCreditToZone -= receiverHeatGain;
    } // calc receiver heat gains

    // Sum up all the case and walk-in loads served by the secondary loop
    if (this->NumCases > 0) {
        for (int caseNum = 1; caseNum <= this->NumCases; ++caseNum) {
            int CaseID = this->CaseNum(caseNum);
            RefrigCase(CaseID).CalculateCase(state);
            // increment TotalCoolingLoad Hot gas/brine defrost credits for each secondary loop
            RefrigerationLoad += RefrigCase(CaseID).TotalCoolingLoad;
            TotalHotDefrostCondCredit += RefrigCase(CaseID).HotDefrostCondCredit;
        } // CaseNum
    } // NumCases > 0
    if (this->NumWalkIns > 0) {
        for (int WalkInIndex = 1; WalkInIndex <= this->NumWalkIns; ++WalkInIndex) {
            int WalkInID = this->WalkInNum(WalkInIndex);
            WalkIn(WalkInID).CalculateWalkIn(state);
            // increment TotalCoolingLoad for  each system
            RefrigerationLoad += WalkIn(WalkInID).TotalCoolingLoad;
            TotalHotDefrostCondCredit += WalkIn(WalkInID).HotDefrostCondCredit;
        } // NumWalkIns systems
    } // Secondary(SecondaryNum)%NumWalkIns > 0

    if (this->NumCoils > 0) {
        for (int CoilIndex = 1; CoilIndex <= this->NumCoils; ++CoilIndex) {
            int CoilID = this->CoilNum(CoilIndex);
            // already CALL CalculateCoil(CoilID) for each coil, dispatched in coilset order for each zone
            // increment TotalCoolingLoad for each system
            //  here will find out if secondary can serve total load, if not will derate coil output/case credits
            RefrigerationLoad += WarehouseCoil(CoilID).TotalCoolingLoad;
            TotalHotDefrostCondCredit += WarehouseCoil(CoilID).HotDefrostCondCredit;
        } // NumCoils on secondary system
    } // Secondary(SecondaryNum)%NumCoils > 0

    TotalLoad = RefrigerationLoad + distPipeHeatGain + receiverHeatGain;
    AtPartLoad = true;
    // Check to see if load is already >+ maxload without pump heat
    if (this->FluidType == SecFluidType::AlwaysLiquid) { //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        FlowVolNeeded = TotalLoad / this->HeatExchangeEta / (CpBrine * DensityBrine * (TBrineIn - this->TEvapDesign));
        // For brine/glycol systems, find flow volume needed to meet load
        // Per ashrae 2006, p4.1, eval mass flow rate to pump at brine return (to chiller) temp
        //   because pumps located in return piping
        if (FlowVolNeeded >= this->MaxVolFlow) {
            // Don't need to iterate on pumps, just set to max.  Will have unmet load this time step (unless coils present)
            VolFlowRate = this->MaxVolFlow;
            TotalPumpPower = this->PumpTotRatedPower;
            TotalLoad += TotalPumpPower * this->PumpPowerToHeat;
            AtPartLoad = false;
            if (this->NumCoils > 0) {
                DeRate = true;
            }
        } // flowvolneeded >= maxvolflow
    } else { // have SecFluidTypePhaseChange !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        if (TotalLoad >= this->MaxLoad) {
            TotalPumpPower = this->PumpTotRatedPower;
            TotalLoad += TotalPumpPower * this->PumpPowerToHeat;
            VolFlowRate = this->MaxVolFlow;
            AtPartLoad = false;
            if (this->NumCoils > 0) {
                DeRate = true;
            }
        }
    } // fluid type check for max load or max flow       >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    // If totalLoad < maxload, then need to calculate partial pump load
    // Need an iterative soln for pump energy needed to meet total load
    //  because that total load has to include pump energy
    if (AtPartLoad) {
        for (Iter = 1; Iter <= 10; ++Iter) {
            if (TotalLoad <= 0.0) {
                // Load on secondary loop is zero (or negative).
                // Set volumetric flow rate and pump power to be zero.
                VolFlowRate = 0.0;
                TotalPumpPower = 0.0;
                break;
            }
            PrevTotalLoad = TotalLoad;
            if (this->FluidType == SecFluidType::AlwaysLiquid) {
                FlowVolNeeded = TotalLoad / this->HeatExchangeEta / (CpBrine * DensityBrine * (TBrineIn - this->TEvapDesign));
                PartLdFrac = FlowVolNeeded / this->MaxVolFlow;
            } else {
                PartLdFrac = TotalLoad / this->MaxLoad;
            }
            if (this->PumpControlType == SecPumpCtrl::Constant) {
                VolFlowRate = 0.0;
                TotalPumpPower = 0.0;
                for (int PumpID = 1; PumpID <= this->NumPumps; ++PumpID) { // dispatch pumps to meet needed flow rate
                    if (this->FluidType == SecFluidType::AlwaysLiquid) {   //>>>>>>>>>>>>>>>>>>>>>
                        VolFlowRate += this->PumpIncrementFlowVol;
                        TotalPumpPower += this->PumpIncrementPower;
                        if (VolFlowRate >= FlowVolNeeded) {
                            break;
                        }
                    } else { // fluid type phase change >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
                        VolFlowRate += this->PumpIncrementFlowVol;
                        TotalPumpPower += this->PumpIncrementPower;
                        PartPumpFrac = TotalPumpPower / this->PumpTotRatedPower;
                        if (PartPumpFrac >= PartLdFrac) {
                            break;
                        }
                    } // fluid type              >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
                } // Dispatching pumps until fluid flow need is met
            } else { // pump type variable
                VarFrac = max(0.1, Curve::CurveValue(state, this->VarSpeedCurvePtr, PartLdFrac));
                TotalPumpPower = this->PumpTotRatedPower * VarFrac;
                VolFlowRate = this->MaxVolFlow * PartLdFrac;
            } // pump type

            TotalLoad = RefrigerationLoad + distPipeHeatGain + receiverHeatGain + TotalPumpPower * this->PumpPowerToHeat;
            Error = std::abs((TotalLoad - PrevTotalLoad) / PrevTotalLoad);
            if (Error < ErrorTol) {
                break;
            }
        } // end iteration on pump energy convergence

        //   IF (Iter >=10 .AND. .NOT. WarmupFlag)THEN
        //     If( .not. WarmupFlag) Then
        //      Write(OutputFileDebug,707)Month, DataGlobals::CurrentTime, Iter, TotalLoad, TotalPumpPower
        //     End If
        // 707 format(' in iter loop at 707: ',1x,I2,1x,F5.2,1x,I5,7(F10.5,1x))
        //    END IF  !didn't converge
    } //(AtPartLoad)

    // If only loads are cases and walk-ins, that is, no air coils:
    //  Account for difference between load and capacity on secondary loop. Assume system able to provide
    //  rated capacity.  If it can't, that unmet energy will be stored and discharged at the system level.
    //  Meet current load to the extent possible.  If extra capacity available,
    //  apply it to previously unmet/stored loads.  If capacity less than current load,
    //  (e.g. as it may be following defrost cycles on cases or walk-ins served by secondary loop)
    //  save the unmet/stored load to be met in succeeding time steps.
    if (this->NumCoils == 0) {
        StoredEnergyRate = max(0.0, (this->UnmetEnergy / state.dataGlobal->TimeStepZone / Constant::rSecsInHour));
        // Load necessary to meet current and all stored energy needs (W)
        Real64 LoadRequested = TotalLoad + StoredEnergyRate;
        if (this->MaxLoad > LoadRequested) {
            // Have at least as much capacity avail as needed, even counting stored energy
            this->TotalCoolingLoad = LoadRequested;
            RefrigerationLoad += StoredEnergyRate;
            this->UnmetEnergy = 0.0;
        } else {
            // Don't have as much capacity as needed (likely following defrost periods)
            this->TotalCoolingLoad = this->MaxLoad;
            RefrigerationLoad -= (TotalLoad - this->MaxLoad);
            if (!state.dataGlobal->WarmupFlag) {
                this->UnmetEnergy += ((TotalLoad - this->MaxLoad) * state.dataGlobal->TimeStepZoneSec);
            }
        } // load requested greater than MaxLoad
        if (this->UnmetEnergy > MyLargeNumber) {
            this->UnmetEnergy = MyLargeNumber;
            if (state.dataRefrigCase->ShowUnmetSecondEnergyWarning(SecondaryNum)) {
                ShowWarningError(state, format("Secondary Refrigeration Loop: {}", this->Name));
                ShowContinueError(state, " This secondary system has insufficient capacity to meet the refrigeration loads.");
                state.dataRefrigCase->ShowUnmetSecondEnergyWarning(SecondaryNum) = false;
            }
        } //>my large number

    } else { // air coils on secondary loop, no "unmet" energy accounting, just reduce amount of cooling provided to zone by coils
        DeRate = false;
        if (TotalLoad > this->MaxLoad) {
            DeRate = true;
        }
        FinalRateCoils(
            state, DeRate, SourceType::SecondarySystem, SecondaryNum, TotalLoad, this->MaxLoad); // assign case credits for coils on this loop
        // Bug TotalCoolingLoad not set but used below
    } // no air coils on secondary loop
    this->PumpPowerTotal = TotalPumpPower;
    this->PumpElecEnergyTotal = TotalPumpPower * localTimeStepSec;
    this->TotalRefrigLoad = RefrigerationLoad;
    this->TotalRefrigEnergy = RefrigerationLoad * localTimeStepSec;
    this->TotalCoolingEnergy = TotalCoolingLoad * localTimeStepSec;
    this->FlowVolActual = VolFlowRate;
    this->HotDefrostCondCredit = TotalHotDefrostCondCredit;
    this->DistPipeHeatGain = distPipeHeatGain;
    this->DistPipeHeatGainEnergy = distPipeHeatGain * localTimeStepSec;
    this->ReceiverHeatGain = receiverHeatGain;
    this->ReceiverHeatGainEnergy = receiverHeatGain * localTimeStepSec;
}

void SumZoneImpacts(EnergyPlusData &state)
{

    // SUBROUTINE INFORMATION:
    //       AUTHOR         Therese Stovall, ORNL
    //       DATE WRITTEN   Spring 2010
    //       RE-ENGINEERED  na

    // PURPOSE OF THIS SUBROUTINE:
    // Find the total impact of all refrigeration systems on each zone.

    // METHODOLOGY EMPLOYED:
    // Calculate the energy from refrigerated case credits arising from interaction between the zone and:
    //   refrigerated cases and walk-ins
    //   heat rejection from zone-located compressor-racks and zone-located air-cooled condensers
    //   heat absorbed by suction piping, secondary loop distribution piping, and
    //   secondary receiver shells

    auto &CoilSysCredit = state.dataRefrigCase->CoilSysCredit;
    auto &CaseWIZoneReport = state.dataRefrigCase->CaseWIZoneReport;

    if (state.dataRefrigCase->UseSysTimeStep) { // air chillers
        for (int ZoneNum = 1; ZoneNum <= state.dataGlobal->NumOfZones; ++ZoneNum) {
            auto &credit = CoilSysCredit(ZoneNum);
            credit.ReportH2ORemovedKgPerS_FromZoneRate = -credit.LatKgPerS_ToZoneRate;
            credit.ReportLatCreditToZoneRate = -credit.LatCreditToZoneRate;
            credit.ReportLatCreditToZoneEnergy = -credit.LatCreditToZoneEnergy;
            // Sensible rate can be positive or negative, split into separate output variables and
            //   always report positive value
            if (credit.SenCreditToZoneRate <= 0.0) {
                credit.ReportSenCoolingToZoneRate = -credit.SenCreditToZoneRate;
                credit.ReportSenCoolingToZoneEnergy = -credit.SenCreditToZoneEnergy;
                credit.ReportHeatingToZoneRate = 0.0;
                credit.ReportHeatingToZoneEnergy = 0.0;
            } else {
                credit.ReportSenCoolingToZoneRate = 0.0;
                credit.ReportSenCoolingToZoneEnergy = 0.0;
                credit.ReportHeatingToZoneRate = credit.SenCreditToZoneRate;
                credit.ReportHeatingToZoneEnergy = -credit.SenCreditToZoneEnergy;
            }
            credit.ReportTotCoolingToZoneRate = credit.ReportLatCreditToZoneRate + credit.ReportSenCoolingToZoneRate;
            credit.ReportTotCoolingToZoneEnergy = credit.ReportLatCreditToZoneEnergy + credit.ReportSenCoolingToZoneEnergy;
        }
    } // UseSysTimeStep signals run for air chillers

    // Can arrive here when load call to refrigeration looks for cases/walkin systems and usetimestep is .FALSE.
    if ((!state.dataRefrigCase->UseSysTimeStep) &&
        ((state.dataRefrigCase->NumSimulationCases > 0) || (state.dataRefrigCase->NumSimulationWalkIns > 0))) {
        for (int ZoneNum = 1; ZoneNum <= state.dataGlobal->NumOfZones; ++ZoneNum) {
            auto &report = CaseWIZoneReport(ZoneNum);
            report.SenCaseCreditToZoneEnergy = state.dataHeatBal->RefrigCaseCredit(ZoneNum).SenCaseCreditToZone * state.dataGlobal->TimeStepZoneSec;
            // Latent always negative
            report.LatCoolingToZoneRate = -state.dataHeatBal->RefrigCaseCredit(ZoneNum).LatCaseCreditToZone;
            report.LatCoolingToZoneEnergy = report.LatCoolingToZoneRate * state.dataGlobal->TimeStepZoneSec;
            // Sensible rate can be positive or negative, split into separate output variables and
            //   always report positive value
            if (state.dataHeatBal->RefrigCaseCredit(ZoneNum).SenCaseCreditToZone <= 0.0) {
                report.SenCoolingToZoneRate = -state.dataHeatBal->RefrigCaseCredit(ZoneNum).SenCaseCreditToZone;
                report.SenCoolingToZoneEnergy = -state.dataHeatBal->RefrigCaseCredit(ZoneNum).SenCaseCreditToZone * state.dataGlobal->TimeStepZoneSec;
                report.HeatingToZoneRate = 0.0;
                report.HeatingToZoneEnergy = 0.0;
            } else {
                report.SenCoolingToZoneRate = 0.0;
                report.SenCoolingToZoneEnergy = 0.0;
                report.HeatingToZoneRate = state.dataHeatBal->RefrigCaseCredit(ZoneNum).SenCaseCreditToZone;
                report.HeatingToZoneEnergy = state.dataHeatBal->RefrigCaseCredit(ZoneNum).SenCaseCreditToZone * state.dataGlobal->TimeStepZoneSec;
            }
            report.TotCoolingToZoneRate = report.SenCoolingToZoneRate + report.LatCoolingToZoneRate;
            report.TotCoolingToZoneEnergy = report.SenCoolingToZoneEnergy + report.LatCoolingToZoneEnergy;
            report.TotHtXferToZoneRate =
                state.dataHeatBal->RefrigCaseCredit(ZoneNum).SenCaseCreditToZone + state.dataHeatBal->RefrigCaseCredit(ZoneNum).LatCaseCreditToZone;
            report.TotHtXferToZoneEnergy = report.TotHtXferToZoneRate * state.dataGlobal->TimeStepZoneSec;
        } // over zones for cases and walkins
    }
}

void CheckRefrigerationInput(EnergyPlusData &state)
{

    // SUBROUTINE INFORMATION:
    //       AUTHOR         Linda Lawrie
    //       DATE WRITTEN   Sep 2010 - mining function
    //       MODIFIED       na
    //       RE-ENGINEERED  na

    // PURPOSE OF THIS SUBROUTINE:
    // Provides the structure to get Refrigeration input so that
    // it can be called from internally or outside the module.

    if (state.dataRefrigCase->GetRefrigerationInputFlag) {

        GetRefrigerationInput(state);
        SetupReportInput(state);
        state.dataRefrigCase->GetRefrigerationInputFlag = false;

        if ((!state.dataRefrigCase->HaveCasesOrWalkins) && (!state.dataRefrigCase->HaveChillers)) {
            state.dataRefrigCase->ManageRefrigeration = false;
            return;
        }
        if ((!state.dataRefrigCase->HaveDetailedRefrig) && (!state.dataRefrigCase->HaveRefrigRacks) &&
            (!state.dataRefrigCase->HaveDetailedTransRefrig)) {
            state.dataRefrigCase->ManageRefrigeration = false;
            return;
        }
    } // GetRefrigerationInputFlag
}

void SimAirChillerSet(EnergyPlusData &state,
                      std::string const &AirChillerSetName,
                      int const ZoneNum,
                      bool const FirstHVACIteration,
                      Real64 &SysOutputProvided,
                      Real64 &LatOutputProvided,
                      int &AirChillerSetPtr // from ZoneEquipList(CurZoneEqNum)%EquipIndex(EquipPtr)
)
{

    // SUBROUTINE INFORMATION:
    //       AUTHOR         Therese Stovall, ORNL
    //       DATE WRITTEN   January 2011
    //       MODIFIED       na
    //       RE-ENGINEERED  na

    // PURPOSE OF THIS SUBROUTINE:
    // Transfers the load requested from the zone to the refrigeration module.
    // The load is met, partially met, or not met in the call to the detailed system solution
    // METHODOLOGY EMPLOYED:
    // Called from Zone Equipment Manager.

    auto &AirChillerSet = state.dataRefrigCase->AirChillerSet;
    auto &CoilSysCredit = state.dataRefrigCase->CoilSysCredit;

    int ChillerSetID;
    Real64 RemainingOutputToCoolingSP; // Remaining requested load in zone

    CheckRefrigerationInput(state);

    // Find the correct Chiller set
    if (AirChillerSetPtr == 0) {
        ChillerSetID = Util::FindItemInList(AirChillerSetName, AirChillerSet);
        if (ChillerSetID == 0) {
            ShowFatalError(state, format("SimAirChillerSet: Unit not found={}", AirChillerSetName));
        } // chillersetid ==0 because not in list
        AirChillerSetPtr = ChillerSetID;
    } else { // airchllersetpointer passed in call to subroutine not ==0
        ChillerSetID = AirChillerSetPtr;
        if (ChillerSetID > state.dataRefrigCase->NumRefrigChillerSets || ChillerSetID < 1) {
            ShowFatalError(state,
                           format("SimAirChillerSet:  Invalid AirChillerSetPtr passed={}, Number of Units={}, Entered Unit name={}",
                                  ChillerSetID,
                                  state.dataRefrigCase->NumRefrigChillerSets,
                                  AirChillerSetName));
        } // ChillerSetID makes no sense
        if (state.dataRefrigCase->CheckChillerSetName(ChillerSetID)) {
            if (AirChillerSetName != AirChillerSet(ChillerSetID).Name) {
                ShowFatalError(state,
                               format("SimAirChillerSet:  Invalid AirChillerSetPtr passed={}, Unit name={}, stored Unit Name for that index={}",
                                      ChillerSetID,
                                      AirChillerSetName,
                                      AirChillerSet(ChillerSetID).Name));
            } // name not equal correct name
            state.dataRefrigCase->CheckChillerSetName(ChillerSetID) = false;
        } // CheckChillerSetName logical test
    } //(AirChillerSetPtr == 0 or else not == 0

    if (FirstHVACIteration) {
        for (ChillerSetID = 1; ChillerSetID <= state.dataRefrigCase->NumRefrigChillerSets;
             ++ChillerSetID) { // bbb what point of do loop, only set one (airchillersetptr) to zero
            AirChillerSet(AirChillerSetPtr).QZnReqSens = 0.0;
        }
    } // FirstHVACIteration

    RemainingOutputToCoolingSP = state.dataZoneEnergyDemand->ZoneSysEnergyDemand(ZoneNum).RemainingOutputReqToCoolSP;
    // RemainingOutputToCoolingSP in Watts, < 0 for cooling demand

    if (RemainingOutputToCoolingSP < 0.0 && state.dataHeatBalFanSys->TempControlType(ZoneNum) != HVAC::SetptType::SingleHeat) {
        AirChillerSet(AirChillerSetPtr).QZnReqSens = RemainingOutputToCoolingSP;
    } else {
        AirChillerSet(AirChillerSetPtr).QZnReqSens = 0.0;
    }

    state.dataRefrigCase->UseSysTimeStep = true;

    ManageRefrigeratedCaseRacks(state);

    state.dataRefrigCase->UseSysTimeStep = false;

    // Return values to Zone Equipment Manager.
    LatOutputProvided = CoilSysCredit(ZoneNum).LatKgPerS_ToZoneRate;
    SysOutputProvided = CoilSysCredit(ZoneNum).SenCreditToZoneRate;
}

void AirChillerSetData::CalculateAirChillerSets(EnergyPlusData &state)
{

    // SUBROUTINE INFORMATION:
    //       AUTHOR         Therese Stovall, ORNL
    //       DATE WRITTEN   January 2011
    //       MODIFIED       na
    //       RE-ENGINEERED  na

    // PURPOSE OF THIS SUBROUTINE:
    // Transfers the load requested from the zone to the refrigeration module.
    // The load is met, partially met, or not met in the next time step when the refrigerated case
    // module is called via case credits. Therefore, by definition, the sensible and latent
    // output provided are zero.
    // METHODOLOGY EMPLOYED:
    // Called from Zone Equipment Manager.
    //       have however done the variable definitions for in and out.

    Real64 AirChillerSetSchedule = 0.0; // Schedule value for air chiller SET
    Real64 QZNReqSens = 0.0;            // Amount of sensible heat needed by the zone, NEGATIVE when cooling needed [W]
    Real64 RemainQZNReqSens = 0.0;      // Remaining amount of sensible heat needed by the zone [W]

    auto &WarehouseCoil = state.dataRefrigCase->WarehouseCoil;

    // Note, all coils in a coil set are in the same zone
    // the coils may be served by different detailed systems
    // The coils are dispatched to meet the load specified in the previous time step in order listed in coilset object
    AirChillerSetSchedule = this->availSched->getCurrentVal();

    if (AirChillerSetSchedule <= 0.0) {
        return;
    }
    QZNReqSens = this->QZnReqSens;
    RemainQZNReqSens = QZNReqSens;

    for (int CoilIndex = 1; CoilIndex <= this->NumCoils; ++CoilIndex) {
        int CoilID = this->CoilNum(CoilIndex);

        WarehouseCoil(CoilID).CalculateCoil(state, RemainQZNReqSens);
        RemainQZNReqSens += WarehouseCoil(CoilID).SensCreditRate;
        // should be a negative minus a negative, so a smaller negative, that is, going toward zero, but senscoolingenergyrate expressed as
        // positive  Need to go over all the coils so that the defrosts occur on schedule, even when the chiller isn't called for at that
        // particular time step  IF(RemainQZNReqSens >=0.0d0)EXIT  !shouldn't be > 0 because limited by request in calculatecoil
        if (RemainQZNReqSens > 0.0) {
            RemainQZNReqSens = 0.0;
        }
    } // CoilIndex
}

void FinalRateCoils(EnergyPlusData &state,
                    bool const DeRate,                 // True if compressor rack or secondary ht exchanger unable to provide capacity
                    SourceType const SystemSourceType, // Secondarysystem or DetailedSystem
                    int const SystemID,                // ID for Secondary loop or detailed system calling for derate
                    Real64 const InitialTotalLoad,     // Load on system or secondary loop as initially calculated [W]
                    Real64 const AvailableTotalLoad    // Load that system or secondary loop is able to serve [W]
)
{

    // SUBROUTINE INFORMATION:
    //       AUTHOR         Therese Stovall, ORNL
    //       DATE WRITTEN   January 2011
    //       MODIFIED       na
    //       RE-ENGINEERED  na

    // PURPOSE OF THIS SUBROUTINE:
    // When compressor system, or secondary loop capacity is insufficient to meet coil loads
    //   Come back here and derate the coil case credits to show unmet load impact
    //   Note that the coil fan, heater, and defrost would be unaffected because they
    //   would still be running at level calculated previously

    auto &System = state.dataRefrigCase->System;
    auto &WarehouseCoil = state.dataRefrigCase->WarehouseCoil;

    int NumCoils = 0;
    Real64 DeRateFactor = 0.0;        // Ratio of energy available from system or secondary loop
    Real64 InitLatCreditEnergy = 0.0; // Latent credit energy before derate [W]
    Real64 FrostReduction = 0.0;      // Change in frost on coils based on derated latent load [kg]

    {
        switch (SystemSourceType) {
        case SourceType::DetailedSystem:
            NumCoils = System(SystemID).NumCoils;
            break;
        case SourceType::SecondarySystem:
            NumCoils = state.dataRefrigCase->Secondary(SystemID).NumCoils;
            break;
        default:
            assert(false);
        }
    } // DeRateCoils

    if (DeRate) {
        ShowRecurringWarningErrorAtEnd(
            state,
            "Refrigeration:System chilling WarehouseCoils " + System(SystemID).Name +
                " - Refrigeration system unable to meet load of warehouse coils chilled by system ... continues by derating coil load",
            System(SystemID).InsuffCapWarn);

        DeRateFactor = AvailableTotalLoad / InitialTotalLoad;
        Real64 const time_step_sec(state.dataHVACGlobal->TimeStepSysSec);
        for (int CoilIndex = 1; CoilIndex <= NumCoils; ++CoilIndex) {
            int CoilID = System(SystemID).CoilNum(CoilIndex);
            auto &warehouse_coil = WarehouseCoil(CoilID);

            // need to adjust ice on coil due to reduction in latent load met by coil
            InitLatCreditEnergy = warehouse_coil.LatCreditEnergy;

            warehouse_coil.TotalCoolingLoad *= DeRateFactor;
            warehouse_coil.TotalCoolingEnergy *= DeRateFactor;
            warehouse_coil.SensCoolingEnergyRate *= DeRateFactor;
            warehouse_coil.SensCoolingEnergy *= DeRateFactor;
            warehouse_coil.LatCreditRate *= DeRateFactor;
            warehouse_coil.LatCreditEnergy *= DeRateFactor;
            warehouse_coil.LatKgPerS_ToZone *= DeRateFactor;
            warehouse_coil.SensCreditRate = warehouse_coil.SensCoolingEnergyRate - warehouse_coil.ElecFanPower - warehouse_coil.ElecHeaterPower -
                                            warehouse_coil.ThermalDefrostPower;
            warehouse_coil.SensCreditEnergy = warehouse_coil.SensCreditRate * time_step_sec;

            FrostReduction = (InitLatCreditEnergy - warehouse_coil.LatCreditEnergy) / IcetoVaporEnthalpy;
            warehouse_coil.KgFrost = max(0.0, warehouse_coil.KgFrost - FrostReduction);

            if (warehouse_coil.SensCreditRate >= 0.0) {
                warehouse_coil.ReportSensCoolCreditRate = warehouse_coil.SensCreditRate;
                warehouse_coil.ReportHeatingCreditRate = 0.0;
            } else {
                warehouse_coil.ReportSensCoolCreditRate = 0.0;
                warehouse_coil.ReportHeatingCreditRate = -warehouse_coil.SensCreditRate;
            }
            warehouse_coil.ReportSensCoolCreditEnergy = warehouse_coil.ReportSensCoolCreditRate * time_step_sec;
            warehouse_coil.ReportHeatingCreditEnergy = warehouse_coil.ReportHeatingCreditRate * time_step_sec;
            warehouse_coil.ReportTotalCoolCreditRate = warehouse_coil.ReportSensCoolCreditRate + warehouse_coil.LatCreditRate;
            warehouse_coil.ReportTotalCoolCreditEnergy = warehouse_coil.ReportSensCoolCreditEnergy + warehouse_coil.LatCreditEnergy;
        }
    } // DeRate == true
}

void WarehouseCoilData::CalculateCoil(EnergyPlusData &state, Real64 const QZnReq)
{

    // SUBROUTINE INFORMATION:
    //       AUTHOR         Therese Stovall, ORNL
    //       DATE WRITTEN   January 2011
    //       MODIFIED       na
    //       RE-ENGINEERED  na

    // PURPOSE OF THIS SUBROUTINE:
    // Simulates the refrigerated warehouse coil object.
    // Note QZnReq < 0 corresponds to cooling needed

    // METHODOLOGY EMPLOYED:
    // Called from Calculate Air Chiller Set.
    // Air chillers are used to model the type of equipment typically used in
    // refrigerated warehouses. For that reason, there is a major difference
    // between the air chiller model and those for refrigerated cases or walk-ins.
    // For cases and walk-ins, a portion of the model is directed toward
    // calculating the amount of refrigeration needed to maintain the refrigerated
    // volume at the desired temperature due to heat exchange with the surrounding
    // zone, and that zone is conditioned to a nearly constant temperature.
    // In a refrigerated warehouse, the refrigeration load is caused by heat exchange
    // with a variable external environment.  For that reason, the loads for these
    // zones are calculated by the usual EnergyPlus zone heat balance.
    // The amount of refrigeration needed to maintain the specified temperature
    // setpoints is then passed to the air chiller model, in a similar fashion
    // to the load passed to a window air conditioner model. The air chillers
    // are therefore solved using the system time step, not the zone time step
    // used for cases and walk-ins.
    // The air chiller performance is based on three types of manufacturers ratings,
    // Unit Load Factor, Total Capacity Map, or a set of European standards.
    // Correction factors for material and refrigerant are applied to all of these ratings.

    static constexpr std::string_view TrackMessage("from RefrigeratedCase:CalculateCoil");

    Real64 CoilSchedule = this->availSched->getCurrentVal(); // Current value of Coil operating (availability) schedule
    if (CoilSchedule <= 0.0) {
        return;
    }

    Real64 DefrostSchedule = this->defrostSched->getCurrentVal();                 // Coil defrost schedule, between 0 and 1
    Real64 DefrostDripDownSchedule = this->defrostDripDownSched->getCurrentVal(); // Coil drip-down schedule (allows coil to drain after defrost)
    // next statement In case user doesn't understand concept of drip down schedule
    DefrostDripDownSchedule = max(DefrostDripDownSchedule, DefrostSchedule);
    // next value optional, so set to default before checking for schedule
    Real64 HeaterSchedule = 1.0; // zero to one
    if (this->heaterAvailSched != nullptr) {
        HeaterSchedule = this->heaterAvailSched->getCurrentVal();
    }

    // Set local subroutine variables for convenience
    FanSpeedCtrlType FanSpeedControlType = this->FanType;
    Real64 AirVolumeFlowRated = this->RatedAirVolumeFlow;   // Coil rated air flow (m3/s)
    Real64 FanPowerRated = this->RatedFanPower;             // (W)
    Real64 HeaterLoad = this->HeaterPower * HeaterSchedule; // Total heater (except defrost) energy rate (W)
    Real64 DefrostCap = this->DefrostCapacity;              // Design defrost capacity of Coil (W)
    Real64 TEvap = this->TEvapDesign;                       // Evaporating temperature in the coil (C)

    Real64 CoilCapTotEstimate(0.0); // Part of loop to solve for total coil capacity as a function of inlet air conditions (W)
    Real64 AirVolumeFlowMax(0.0);   // Coil air flow limited by drip down schedule (m3/s)
    Real64 CoilCapTotal(0.0);       // Sensible plus latent load (W)
    Real64 CoilInletDensity(0.0);   // Coil air inlet density (kg/m3)
    Real64 CoilInletDryAirCp(0.0);  // Dry air specific heat at coil inlet temperature (J/kg-C)
    Real64 CoilInletHumRatio(0.0);  // Coil air inlet humidity ratio (kg water/kg air)
    Real64 CoilInletTemp(0.0);      // Inlet temperature of air to coil, not mixed zone temperature unless "middle" location selected (C)
    Real64 CoilInletEnthalpy(0.0);  // Coil inlet air enthalpy (J/kg)
    Real64 CoilInletRHFrac(0.0);    // Coil inlet air relative humidity expressed as a fraction (0 to 1)
    Real64 DefrostLoad(0.0);
    Real64 DryAirMassFlowMax(0.0);      // Rated volume flow rate times dry air density adjusted for schedules (kg/s)
    Real64 FanPowerActual(0.0);         // (W)
    Real64 FrostChangekg(0.0);          // Amount of frost added or melted  (kg)
    Real64 latLoadServed(0.0);          // Energy rate used to remove water from zone air (W)
    Real64 SensLoadRequestedGross(0.0); // Gross sensible load removed by coil
    Real64 SensLoadGross(0.0);          // Sensible load met by coil (W)
    Real64 SHR(0.0);                    // Sensible heat ratio, sensible load/total load
    Real64 SHRCorrection(0.0);          // Actual total/sensible load, NOT = Inverse SHR (unless coil efficiency = 1.0)
    Real64 WaterRemovRate(0.0);         // Walk in cooler removes water at this rate in this zone (kg/s)

    if (DefrostDripDownSchedule == 1.0) {
        AirVolumeFlowMax = 0.0;
        DryAirMassFlowMax = 0.0;
    } else { // DefrostDripDownSchedule < 1.0d0, cooling will occur at least part of the time step
        // Sensible load requested by zone balance (W)
        Real64 SensLoadRequested = -QZnReq; // here let cooling demand be positive within subroutine
        if (SensLoadRequested <= 0.0) {     // No load so assume control keeps off, except that scheduled defrost still occurs
            AirVolumeFlowMax = 0.0;
            DryAirMassFlowMax = 0.0;
        } else {
            SensLoadRequestedGross = SensLoadRequested + HeaterLoad + FanPowerRated;
            Real64 ZoneMixedAirDryBulb = state.dataLoopNodes->Node(this->ZoneNodeNum).Temp;    // (C)
            Real64 ZoneMixedAirHumRatio = state.dataLoopNodes->Node(this->ZoneNodeNum).HumRat; // kg water/kg air in the zone mixed air
            Real64 ZoneMixedAirRHFrac =
                Psychrometrics::PsyRhFnTdbWPb(state, ZoneMixedAirDryBulb, ZoneMixedAirHumRatio, state.dataEnvrn->OutBaroPress, TrackMessage);
            Real64 ZoneMixedAirEnthalpy =
                Psychrometrics::PsyHFnTdbRhPb(state, ZoneMixedAirDryBulb, ZoneMixedAirRHFrac, state.dataEnvrn->OutBaroPress, TrackMessage);
            Real64 ZoneMixedAirDensity =
                Psychrometrics::PsyRhoAirFnPbTdbW(state, state.dataEnvrn->OutBaroPress, ZoneMixedAirDryBulb, ZoneMixedAirHumRatio, TrackMessage);
            Real64 ZoneDryAirDensity =
                Psychrometrics::PsyRhoAirFnPbTdbW(state, state.dataEnvrn->OutBaroPress, ZoneMixedAirDryBulb, 0.0, TrackMessage);
            Real64 DryAirMassFlowRated = AirVolumeFlowRated * ZoneDryAirDensity;
            // calc t inlet to coil assuming at middle/mixed point in room  bbb -
            //    later need to do for hottest/coolest in room where Tin /= Tzonemixed
            // calc RH inlet to coil assuming at middle/mixed point in room
            // calc coilcap, sens and latent, available as f(inlet T,RH)
            switch (this->VerticalLocation) {
            case VerticalLoc::Floor:
                // purposely fall through
            case VerticalLoc::Ceiling:
                // purposely fall through
            case VerticalLoc::Middle:
                CoilInletTemp = ZoneMixedAirDryBulb;
                CoilInletEnthalpy = ZoneMixedAirEnthalpy;
                CoilInletRHFrac = ZoneMixedAirRHFrac;
                CoilInletDensity = ZoneMixedAirDensity;
                CoilInletHumRatio = ZoneMixedAirHumRatio;
                CoilInletDryAirCp = Psychrometrics::PsyCpAirFnW(0.0);
                break;
            default:
                assert(false);
            }
            AirVolumeFlowMax = AirVolumeFlowRated * (1.0 - DefrostDripDownSchedule) * CoilSchedule;
            DryAirMassFlowMax = DryAirMassFlowRated * (1.0 - DefrostDripDownSchedule) * CoilSchedule;

        } // Sens load requested is non-zero
    } // DefrostDripDownSchedule == 1.0d0

    if (AirVolumeFlowMax > 0.0) {

        Real64 TemperatureDif =
            min(this->MaxTemperatureDif, (CoilInletTemp - TEvap)); // difference between inlet air and evaporating temperature (deltaC)

        if (this->ratingType == RatingType::RatedCapacityTotal) {
            // RatingType = CapacityTotalSpecificConditions, will be doing a table lookup
            //    based upon RHInlet, DT1, CoilInletTemperature - see excel files from B. Nelson, CoilCom
            //    In the table, X1== inlet air dry bulb temperature
            //                  X2== Difference between inlet T and evap T
            //                  X3== RH expressed as decimal
            CoilCapTotEstimate = Curve::CurveValue(state, this->SHRCorrectionCurvePtr, CoilInletTemp, TemperatureDif, CoilInletRHFrac) *
                                 this->RatedCapTotal * (1.0 - DefrostDripDownSchedule) * CoilSchedule;

        } else { // work with unit load factor (sensible only), function of DT1 (Tair in drybulb-Tevap)
            Real64 SensibleCapacityMax = this->UnitLoadFactorSens * TemperatureDif * (1.0 - DefrostDripDownSchedule) *
                                         CoilSchedule; // Sensible capacity adjusted for any time in dripdown state (W)

            if (SensibleCapacityMax > 0.0) {
                Real64 ExitTemperatureEstimate =
                    CoilInletTemp - (SensibleCapacityMax / (DryAirMassFlowMax * CoilInletDryAirCp)); // Estimated Air temperature leaving the coil (C)
                if (ExitTemperatureEstimate <= TEvap) {
                    ShowWarningError(state, format("{}Refrigeration:AirCoil: {}", TrackMessage, this->Name));
                    ShowContinueError(state, " The estimated air outlet temperature is less than the evaporating temperature.");
                }
                Real64 ExitEnthalpyEstimate = Psychrometrics::PsyHFnTdbRhPb(state,
                                                                            ExitTemperatureEstimate,
                                                                            1.0,
                                                                            state.dataEnvrn->OutBaroPress,
                                                                            TrackMessage); // Estimated Air enthalpy leaving the coil (J/kg)
                if (ExitEnthalpyEstimate <= CoilInletEnthalpy) {
                    CoilCapTotEstimate = (CoilInletEnthalpy - ExitEnthalpyEstimate) * AirVolumeFlowMax * CoilInletDensity;
                } else {
                    // Assume no water is extracted from flow
                    ExitEnthalpyEstimate = Psychrometrics::PsyHFnTdbW(ExitTemperatureEstimate, CoilInletHumRatio);
                    CoilCapTotEstimate = (CoilInletEnthalpy - ExitEnthalpyEstimate) * AirVolumeFlowMax * CoilInletDensity;
                }
                if (SensibleCapacityMax > CoilCapTotEstimate) {
                    SensibleCapacityMax = CoilCapTotEstimate;
                }
                if (std::abs(CoilCapTotEstimate) > 0.0) {
                    SHR = SensibleCapacityMax / (CoilCapTotEstimate);
                } else {
                    // will occur whenever defrost or dripdown
                    SHR = 0.0;
                }

                switch (this->SHRCorrType) {
                case SHRCorrectionType::SHR60: {
                    // line from y = SHRCorrection60 value to 1. as x(SHR) goes from .6 to 1, from B. Nelson, ASHRAE August 2010
                    Real64 Slope = (this->SHRCorrection60 - 1.0) / (0.6 - 1.0); // Part of linear SHR60 correction factor, dimensionless
                    Real64 Yint = this->SHRCorrection60 - (Slope * 0.6);        // Part of linear SHR60 correction factor, dimensionless
                    SHRCorrection = Slope * SHR + Yint;
                } break;
                case SHRCorrectionType::QuadraticSHR: {
                    SHRCorrection = Curve::CurveValue(state, this->SHRCorrectionCurvePtr, SHR);
                } break;
                case SHRCorrectionType::European: {
                    // With European ratings, either start with rated total sensible capacity or rated total capacity
                    //    If rated total capacity is used, 'get input'
                    //    translated it to rated total sensible capacity using
                    //    PARAMETER ::EuropeanWetCoilFactor = (/1.35D0, 1.15D0,  1.05D0,  1.01D0,   1.0D0/)
                    //    That sensible capacity rating was then turned to a rated UnitLoadFactor using
                    //    the rated temperature difference. That sensible rating was also corrected
                    //    for refrigerant and fin material in 'get input' and is given as UnitLoadFactor
                    //  The total (sens + latent) capacity is equal to that * DT1 * WetCoilFactor(TcoilIn)
                    //    Sensible capacity max already has DT1, just need WetCoilFactor(TcoilIn)
                    // PARAMETER ::EuropeanWetCoilFactor = (/1.35D0, 1.15D0,  1.05D0,  1.01D0,   1.0D0/)
                    // PARAMETER ::EuropeanAirInletTemp  = (/10.0D0,  0.0D0, -18.0D0, -25.0D0, -34.0D0/)
                    // PARAMETER ::EuropeanEvapTemp      = (/ 0.0D0, -8.0D0, -25.0D0, -31.0D0, -40.0D0/)
                    // PARAMETER ::EuropeanDT1           = (/10.0D0,  8.0D0,   7.0D0,   7.0D0,   6.0D0/)
                    if (CoilInletTemp <= -25.0) {
                        SHRCorrection = 1.0;
                    } else if (CoilInletTemp > -25.0 && CoilInletTemp <= 0.0) {
                        SHRCorrection = (EuropeanWetCoilFactor[1] - EuropeanWetCoilFactor[3]) / (EuropeanAirInletTemp[1] - EuropeanAirInletTemp[3]) *
                                            (EuropeanAirInletTemp[1] - CoilInletTemp) +
                                        EuropeanWetCoilFactor[3];
                    } else if (CoilInletTemp > 0.0 && CoilInletTemp <= 5.0) {
                        SHRCorrection = (EuropeanWetCoilFactor[0] - EuropeanWetCoilFactor[1]) / (EuropeanAirInletTemp[0] - EuropeanAirInletTemp[1]) *
                                            (EuropeanAirInletTemp[0] - CoilInletTemp) +
                                        EuropeanWetCoilFactor[1];
                    } else if (CoilInletTemp > 5.0) {
                        SHRCorrection = EuropeanWetCoilFactor[0];
                    } // calc correction as a function of coil inlet temperature
                } break;
                default:
                    break;
                }
                CoilCapTotEstimate = SHRCorrection * SensibleCapacityMax;
            } else { // NOT (SensibleCapacityMax > 0.0d0)
                CoilCapTotEstimate = 0.0;
            } //  (SensibleCapacityMax > 0.0d0)
        } // Rating type : CapacityTotalSpecificConditions or Sensible Unit Load Factor

        if (CoilCapTotEstimate > 0.0) {
            Real64 ExitEnthalpy =
                CoilInletEnthalpy - (CoilCapTotEstimate / (AirVolumeFlowMax * CoilInletDensity)); // Air enthalpy leaving the coil (J/kg)
            Real64 ExitTemperature = Psychrometrics::PsyTsatFnHPb(
                state, ExitEnthalpy, state.dataEnvrn->OutBaroPress, TrackMessage); // RH =1.0 at Tsat // Air temperature leaving the coil (C)
            Real64 ExitHumRatio = Psychrometrics::PsyWFnTdbH(state, ExitTemperature, ExitEnthalpy, TrackMessage); // kg water/kg air
            if (ExitHumRatio > CoilInletHumRatio) {
                ExitHumRatio = CoilInletHumRatio;
            }
            WaterRemovRate = DryAirMassFlowMax * (CoilInletHumRatio - ExitHumRatio);
            latLoadServed = WaterRemovRate * IcetoVaporEnthalpy;
            SensLoadGross = CoilCapTotEstimate - latLoadServed;
            FanPowerActual = FanPowerRated;
            if (SensLoadGross < 0.0) {
                // Could rarely happen during initial cooldown of a warm environment
                SensLoadGross = 0.0;
                latLoadServed = CoilCapTotEstimate;
                WaterRemovRate = latLoadServed / IcetoVaporEnthalpy;
            } // SensLoadGross < 0
        } else { // NOT (SensibleCapacityMax > 0.0d0)
            WaterRemovRate = 0.0;
            latLoadServed = 0.0;
            SensLoadGross = 0.0;
            FanPowerActual = 0.0;
        } //(CoilCapTotEstimate > 0.0d0)

        Real64 FanPowerMax = FanPowerRated * (1.0 - DefrostDripDownSchedule); // Total fan energy rate, limited by dripdown period (W)
        if (SensLoadGross > SensLoadRequestedGross) {                         // part load operation
            // don't need full chiller power, reduce fan speed to reduce air flow
            // move fan to part power if need to
            Real64 CapFac = SensLoadRequestedGross / SensLoadGross; // used to reduce fan power when don't need full coil capacity
            Real64 AirVolRatio = max(this->FanMinAirFlowRatio, std::pow(CapFac, EvaporatorAirVolExponent)); // used when operating at part load
            // Fans limited by minimum air flow ratio

            switch (FanSpeedControlType) {
            case FanSpeedCtrlType::VariableSpeed: {                // fan power law, adjusted for reality, applies
                Real64 FanPowerRatio = std::pow(AirVolRatio, 2.5); // Used for variable speed fans, dimensionless
                FanPowerActual = FanPowerRatio * FanPowerMax;
            } break;
            case FanSpeedCtrlType::ConstantSpeed: {
                FanPowerActual = AirVolRatio * std::exp(1.0 - AirVolRatio) * FanPowerMax;
            } break;
            case FanSpeedCtrlType::ConstantSpeedLinear: { // e.g., on-off control
                FanPowerActual = AirVolRatio * FanPowerMax;
            } break;
            case FanSpeedCtrlType::TwoSpeed: {
                // low speed setting of 1/2 fan speed can give up to 60% of capacity.
                // 1/2 speed corresponds to ~1/8 power consumption (FanHalfSpeedRatio = 1/(2**2.5) = 0.1768)
                // dampers are used to control flow within those two ranges as in FanConstantSpeed
                if (CapFac < CapFac60Percent) {
                    FanPowerActual = ((AirVolRatio + 0.4) * (FanHalfSpeedRatio)) * std::exp(1.0 - AirVolRatio) * FanPowerMax;
                } else {
                    FanPowerActual = AirVolRatio * std::exp(1.0 - AirVolRatio) * FanPowerMax;
                } // capfac60percent
            } break;
            default:
                break;
            } // fan speed control type

            // reduce latent capacity according to value called for for sensible  - recalc latent.
            //   recalc coilcaptotal
            WaterRemovRate *= AirVolRatio;
            latLoadServed = WaterRemovRate * IcetoVaporEnthalpy;
            SensLoadGross = SensLoadRequestedGross;
        } else { // at full load
            FanPowerActual = FanPowerMax;
        } // part load and sensload served > 0.

        CoilCapTotal = SensLoadGross + latLoadServed;
        if (CoilCapTotal > 0.0) {
            SHR = SensLoadGross / CoilCapTotal;
        } else {
            SHR = 0.0;
        } //(CoilCapTotal > 0.0d0)

        // now handle ice on coil and defrost because defrost energy not into melting ice goes into sensible load
        // FROST:  keep track of frost build up on evaporator coil
        //         avoid accumulation during warm-up to avoid reverse dd test problem
        if (!state.dataGlobal->WarmupFlag) {
            FrostChangekg = (WaterRemovRate * state.dataHVACGlobal->TimeStepSysSec);
            this->KgFrost += FrostChangekg;
        }

    } else { // NOT (AirVolumeFlowMax > 0.0d0)
        WaterRemovRate = 0.0;
        latLoadServed = 0.0;
        SensLoadGross = 0.0;
        FanPowerActual = 0.0;
    } //(AirVolumeFlowMax > 0.0d0)

    // DEFROST CALCULATIONS   ***** need to reduce sensible heat to zone from
    //                     defrost by amount used to melt ice. Last two elements
    //                     in starting IF are there to mimic temperature override
    //                     on the coils that stops defrost if the coils get above
    //                     a certain temperature (such as when there's no load and no ice)
    if ((DefrostSchedule > 0.0) && (this->defrostType != DefrostType::None) && (this->defrostType != DefrostType::OffCycle)) {
        DefrostLoad = DefrostCap * DefrostSchedule;                                // Part of the defrost that is a heat load on the zone (W)
        Real64 DefrostEnergy = DefrostLoad * state.dataHVACGlobal->TimeStepSysSec; // Joules
        Real64 StartFrostKg = this->KgFrost;                                       // frost load at start of time step (kg of ice)

        if (this->DefrostControlType == DefrostCtrlType::TempTerm) {
            //  Need to turn defrost system off early if controlled by temperature and all ice melted
            //  For temperature termination, need to recognize not all defrost heat goes to melt ice
            //  Some goes to misc losses (for fluid defrost, some coil areas bare earlier than
            //  others and xfer heat to environment)
            //  Assume full ice melting satisfies temperature control.
            //      (defaults for DefEnergyFraction are :=0.7 for elec, =0.3 for fluids)
            Real64 AvailDefrostEnergy = this->DefEnergyFraction * DefrostEnergy; // available to melt ice with temp term control (J)
            Real64 IceSensHeatNeeded = 0.0; // Energy to raise frost temperature to 0C, used w/ temp termination (J)
            if (StartFrostKg > 0.0) {
                if (this->IceTemp < 0.0) {
                    Real64 StartIceTemp = this->IceTemp;                                       // Frost temperature at start of time step [C]
                    IceSensHeatNeeded = StartFrostKg * SpecificHeatIce * (0.0 - StartIceTemp); // Joules
                    if (AvailDefrostEnergy >= IceSensHeatNeeded) {
                        this->IceTemp = 0.0;
                        AvailDefrostEnergy -= IceSensHeatNeeded; // Joules
                    } else {                                     // DefrostEnergy < IceSensHeatNeeded
                        this->IceTemp = StartIceTemp + AvailDefrostEnergy / (SpecificHeatIce * StartFrostKg);
                        AvailDefrostEnergy = 0.0;
                    } // AvailDefrostEnergy >= IceSensHeatNeeded
                } // IceTemp < 0,  need to raise temperature of ice
                // Reduce defrost heat load on walkin by amount of ice melted during time step
                FrostChangekg = min(AvailDefrostEnergy / IceMeltEnthalpy, StartFrostKg);
                if (FrostChangekg < StartFrostKg) {
                    DefrostLoad -= FrostChangekg * IceMeltEnthalpy / state.dataHVACGlobal->TimeStepSys / Constant::rSecsInHour;
                    if (!state.dataGlobal->WarmupFlag) {
                        this->KgFrost = StartFrostKg - FrostChangekg;
                    }
                    // DefrostSchedule not changed because ice not all melted, temp term not triggered
                } else { // all frost melted during time step, so need to terminate defrost
                    //  see Aug 8 2010 page 3 notes
                    this->KgFrost = 0.0;
                    Real64 DefrostEnergyNeeded = (IceSensHeatNeeded + (FrostChangekg * IceMeltEnthalpy)) /
                                                 this->DefEnergyFraction; // Joules - energy needed including E unavail to melt ice
                    DefrostSchedule = min(DefrostSchedule, (DefrostEnergyNeeded / (DefrostCap * state.dataHVACGlobal->TimeStepSysSec)));
                    // reduce heat load on warehouse by energy put into ice melting
                    // Defrost load that actually goes to melting ice (W)
                    Real64 DefrostRateNeeded = (IceSensHeatNeeded + (FrostChangekg * IceMeltEnthalpy)) / (state.dataHVACGlobal->TimeStepSysSec);
                    DefrostLoad = max(0.0, (DefrostSchedule * DefrostCap - DefrostRateNeeded));
                    this->IceTemp = this->TEvapDesign;
                } // frost melted during time step less than amount of ice at start
            } else {
                // no frost present so terminate defrost and reset ice temperature for start of next defrost
                // However, dripdown schedule still prevents/limits cooling capacity during time step
                DefrostLoad = 0.0;
                DefrostSchedule = 0.0;
                this->IceTemp = this->TEvapDesign;
            } // have frost present

        } else {
            // Not temperature control type, controlled only by schedule
            // Reduce defrost heat load on the zone by amount of ice melted during time step
            // But DefrostSchedule not changed
            FrostChangekg = max(0.0, min((DefrostEnergy / IceMeltEnthalpy), StartFrostKg));
            DefrostLoad -= FrostChangekg * IceMeltEnthalpy / state.dataHVACGlobal->TimeStepSys / Constant::rSecsInHour;
            if (!state.dataGlobal->WarmupFlag) {
                this->KgFrost = StartFrostKg - FrostChangekg;
            }
        } // Temperature termination vs. time-clock control type

    } else { // DefrostSchedule <= 0 or have None or OffCycle
        DefrostLoad = 0.0;
    } // Defrost calculations

    Real64 SensLoadFromZone = SensLoadGross - HeaterLoad - DefrostLoad -
                              FanPowerActual; // Net sensible load removed from zone after accounting for heaters, fans, defrost [W]

    // ReportWarehouseCoil(CoilID)
    this->ThermalDefrostPower = DefrostLoad;
    if (this->defrostType == DefrostType::Elec) {
        this->ElecDefrostConsumption = DefrostCap * DefrostSchedule * state.dataHVACGlobal->TimeStepSysSec;
        this->ElecDefrostPower = DefrostCap * DefrostSchedule;
    } else {
        this->ElecDefrostConsumption = 0.0;
        this->ElecDefrostPower = 0.0;
    }

    // If hot brine or hot gas is used for defrost, need to reduce condenser load by heat reclaimed for defrost
    if (this->defrostType == DefrostType::Fluid) {
        this->HotDefrostCondCredit = DefrostCap * DefrostSchedule;
    }
    // LatentLoadServed is positive for latent heat removed from zone
    // SensLoadFromZone positive for heat REMOVED from zone, switch when do credit to zone
    this->SensCreditRate = SensLoadFromZone;
    this->SensCreditEnergy = SensLoadFromZone * state.dataHVACGlobal->TimeStepSysSec;
    this->LatCreditRate = latLoadServed;
    this->LatCreditEnergy = latLoadServed * state.dataHVACGlobal->TimeStepSysSec;
    this->LatKgPerS_ToZone = WaterRemovRate;
    this->TotalCoolingLoad = CoilCapTotal;
    this->TotalCoolingEnergy = CoilCapTotal * state.dataHVACGlobal->TimeStepSysSec;
    this->SensCoolingEnergyRate = SensLoadGross;
    this->SensCoolingEnergy = SensLoadGross * state.dataHVACGlobal->TimeStepSysSec;
    this->SensHeatRatio = SHR;
    this->ElecFanPower = FanPowerActual;
    this->ElecFanConsumption = FanPowerActual * state.dataHVACGlobal->TimeStepSysSec;
    this->ElecHeaterPower = HeaterLoad;
    this->ElecHeaterConsumption = HeaterLoad * state.dataHVACGlobal->TimeStepSysSec;

    this->TotalElecPower = FanPowerActual + HeaterLoad + this->ElecDefrostPower;
    this->TotalElecConsumption = this->TotalElecPower * state.dataHVACGlobal->TimeStepSysSec;

    if (this->SensCreditRate >= 0.0) {
        this->ReportSensCoolCreditRate = this->SensCreditRate;
        this->ReportHeatingCreditRate = 0.0;
    } else {
        this->ReportSensCoolCreditRate = 0.0;
        this->ReportHeatingCreditRate = -this->SensCreditRate;
    }
    this->ReportSensCoolCreditEnergy = this->ReportSensCoolCreditRate * state.dataHVACGlobal->TimeStepSysSec;
    this->ReportHeatingCreditEnergy = this->ReportHeatingCreditRate * state.dataHVACGlobal->TimeStepSysSec;
    this->ReportTotalCoolCreditRate = this->ReportSensCoolCreditRate + this->LatCreditRate;
    this->ReportTotalCoolCreditEnergy = this->ReportSensCoolCreditEnergy + this->LatCreditEnergy;

    //**************************************************************************************************
    // Cap Kg Frost to avoid floating overflow errors
    // 1-time warning is issued. It should be rare but could happen with unrealistic inputs.

    if (this->KgFrost > MyLargeNumber) {
        this->KgFrost = MyLargeNumber;
        if (this->ShowCoilFrostWarning) {
            ShowWarningError(state, format("Refrigeration:AirCoil: {}", this->Name));
            ShowContinueError(state, " This refrigerated air coil has insufficient defrost capacity to remove the excess frost accumulation.");
            ShowContinueError(state, " Check the defrost schedule or defrost capacity. ");
            ShowContinueErrorTimeStamp(state, "... Occurrence info");
            this->ShowCoilFrostWarning = false;
        }
    }
}

void FigureRefrigerationZoneGains(EnergyPlusData &state)
{

    // SUBROUTINE INFORMATION:
    //       AUTHOR         B. Griffith
    //       DATE WRITTEN   Dec 2011
    //       MODIFIED       na
    //       RE-ENGINEERED  na

    // PURPOSE OF THIS SUBROUTINE:
    // initialize zone gain terms at begin environment

    auto &System = state.dataRefrigCase->System;
    auto &TransSystem = state.dataRefrigCase->TransSystem;
    auto &RefrigRack = state.dataRefrigCase->RefrigRack;
    auto &Secondary = state.dataRefrigCase->Secondary;
    auto &WalkIn = state.dataRefrigCase->WalkIn;
    auto &RefrigCase = state.dataRefrigCase->RefrigCase;

    CheckRefrigerationInput(state);

    if (state.dataGlobal->BeginEnvrnFlag && state.dataRefrigCase->FigureRefrigerationZoneGainsMyEnvrnFlag) {

        if (state.dataRefrigCase->NumRefrigSystems > 0) {
            for (auto &e : System) {
                e.PipeHeatLoad = 0.0;
                e.NetHeatRejectLoad = 0.0;
            }
        }

        if (state.dataRefrigCase->NumTransRefrigSystems > 0) {
            for (auto &e : TransSystem) {
                e.PipeHeatLoadMT = 0.0;
                e.PipeHeatLoadLT = 0.0;
                e.NetHeatRejectLoad = 0.0;
            }
        }

        if (state.dataRefrigCase->NumRefrigeratedRacks > 0) {
            for (auto &e : RefrigRack) {
                e.SensZoneCreditHeatRate = 0.0;
                e.SensHVACCreditHeatRate = 0.0;
            }
        }

        if (state.dataRefrigCase->NumSimulationSecondarySystems > 0) {
            for (auto &e : Secondary) {
                e.DistPipeZoneHeatGain = 0.0;
                e.ReceiverZoneHeatGain = 0.0;
            }
        }

        if (state.dataRefrigCase->NumSimulationWalkIns > 0) {
            for (int loop = 1; loop <= state.dataRefrigCase->NumSimulationWalkIns; ++loop) {
                WalkIn(loop).SensZoneCreditRate = 0.0;
                WalkIn(loop).LatZoneCreditRate = 0.0;
            }
        }
        if (state.dataRefrigCase->NumSimulationCases > 0) {
            for (auto &e : RefrigCase) {
                e.SensZoneCreditRate = 0.0;
                e.SensHVACCreditRate = 0.0;
                e.LatZoneCreditRate = 0.0;
                e.LatHVACCreditRate = 0.0;
            }
        }
        state.dataRefrigCase->FigureRefrigerationZoneGainsMyEnvrnFlag = false;
    }
    if (!state.dataGlobal->BeginEnvrnFlag) {
        state.dataRefrigCase->FigureRefrigerationZoneGainsMyEnvrnFlag = true;
    }
}

void ZeroHVACValues(EnergyPlusData &state)
{

    // SUBROUTINE INFORMATION:
    //       AUTHOR         T. Stovall
    //       DATE WRITTEN   Aug 2012
    //       MODIFIED       na
    //       RE-ENGINEERED  na

    // PURPOSE OF THIS SUBROUTINE:
    // Reset all values that communicate outside module for HVAC steps
    // to zero when called on zone timestep. Otherwise, values may be held over when
    // no HVAC load calls module during that zone time step.

    auto &RefrigRack = state.dataRefrigCase->RefrigRack;
    auto &Condenser = state.dataRefrigCase->Condenser;

    int DemandARRID = 0; // Index to water tank Demand used for evap condenser

    if (state.dataRefrigCase->HaveRefrigRacks) {
        // HaveRefrigRacks is TRUE when NumRefrigeratedRAcks > 0
        // RefrigRack ALLOCATED to NumRefrigeratedRacks
        for (int RackNum = 1; RackNum <= state.dataRefrigCase->NumRefrigeratedRacks; ++RackNum) {
            if (RefrigRack(RackNum).CondenserType == DataHeatBalance::RefrigCondenserType::Water) {
                Real64 MassFlowRate = 0.0;
                PlantUtilities::SetComponentFlowRate(
                    state, MassFlowRate, RefrigRack(RackNum).InletNode, RefrigRack(RackNum).OutletNode, RefrigRack(RackNum).plantLoc);
            }
            if (RefrigRack(RackNum).CondenserType == DataHeatBalance::RefrigCondenserType::Evap) {
                if (RefrigRack(RackNum).EvapWaterSupplyMode == WaterSupply::FromTank) {
                    DemandARRID = RefrigRack(RackNum).EvapWaterTankDemandARRID;
                    int TankID = RefrigRack(RackNum).EvapWaterSupTankID;
                    state.dataWaterData->WaterStorage(TankID).VdotRequestDemand(DemandARRID) = 0.0;
                }
            }
        } // RackNum
    } // HaveRefrigRacks

    if (state.dataRefrigCase->NumRefrigCondensers > 0) {
        // Condenser ALLOCATED to DataHeatBalance::NumRefrigCondensers
        for (int CondID = 1; CondID <= state.dataRefrigCase->NumRefrigCondensers; ++CondID) {
            if (Condenser(CondID).CondenserType == DataHeatBalance::RefrigCondenserType::Water) {
                Real64 MassFlowRate = 0.0;
                PlantUtilities::SetComponentFlowRate(
                    state, MassFlowRate, Condenser(CondID).InletNode, Condenser(CondID).OutletNode, Condenser(CondID).plantLoc);
            }
            if (Condenser(CondID).CondenserType == DataHeatBalance::RefrigCondenserType::Evap) {
                if (Condenser(CondID).EvapWaterSupplyMode == WaterSupply::FromTank) {
                    DemandARRID = Condenser(CondID).EvapWaterTankDemandARRID;
                    int TankID = Condenser(CondID).EvapWaterSupTankID;
                    state.dataWaterData->WaterStorage(TankID).VdotRequestDemand(DemandARRID) = 0.0;
                }
            }
        } // ICond
    } // DataHeatBalance::NumRefrigCondensers>0
}

} // namespace EnergyPlus::RefrigeratedCase
